PHP code example of solidframe / saga

1. Go to this page and download the library: Download solidframe/saga library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

solidframe / saga example snippets


use SolidFrame\Saga\Saga\AbstractSaga;

final class PlaceOrderSaga extends AbstractSaga
{
    public function handleOrderPlaced(OrderPlaced $event): void
    {
        // Correlate saga to order
        $this->associateWith('orderId', $event->orderId);

        // Step 1: Reserve inventory
        $this->reserveInventory($event);

        // Register compensation in case of failure
        $this->addCompensation(fn () => $this->releaseInventory($event->orderId));
    }

    public function handlePaymentCompleted(PaymentCompleted $event): void
    {
        // Step 2: Confirm order
        $this->confirmOrder($event->orderId);
        $this->complete();
    }

    public function handlePaymentFailed(PaymentFailed $event): void
    {
        // Triggers all compensations in reverse order
        $this->fail();
    }

    // ...
}

$saga = new PlaceOrderSaga();

$saga->status();      // SagaStatus::InProgress
$saga->isCompleted(); // false
$saga->isFailed();    // false

// After complete()
$saga->status();      // SagaStatus::Completed
$saga->isCompleted(); // true

// After fail() — compensations execute automatically
$saga->status();      // SagaStatus::Failed
$saga->isFailed();    // true

$saga->associateWith('orderId', 'order-123');
$saga->associateWith('customerId', 'customer-456');

$saga->associations();
// [Association(key: 'orderId', value: 'order-123'), ...]

$saga->removeAssociation('customerId');

$saga = $sagaStore->findByAssociation(
    PlaceOrderSaga::class,
    new Association('orderId', 'order-123'),
);

// Step 1
$this->reserveInventory($orderId);
$this->addCompensation(fn () => $this->releaseInventory($orderId));

// Step 2
$this->chargePayment($orderId);
$this->addCompensation(fn () => $this->refundPayment($orderId));

// On failure: refundPayment() runs first, then releaseInventory()
$this->fail();

$saga->compensate();

use SolidFrame\Saga\Store\SagaStoreInterface;

// Save
$sagaStore->save($saga);

// Find by ID
$saga = $sagaStore->find('saga-id');

// Find by association
$saga = $sagaStore->findByAssociation(
    PlaceOrderSaga::class,
    new Association('orderId', 'order-123'),
);

// Delete
$sagaStore->delete('saga-id');

use SolidFrame\Saga\Store\InMemorySagaStore;

$store = new InMemorySagaStore();

use SolidFrame\Saga\State\SagaStatus;

SagaStatus::InProgress; // 'in_progress' — saga is executing
SagaStatus::Completed;  // 'completed'   — saga finished successfully
SagaStatus::Failed;     // 'failed'      — saga failed, compensations applied