PHP code example of jeromejhipolito / laravel-saga
1. Go to this page and download the library: Download jeromejhipolito/laravel-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/ */
jeromejhipolito / laravel-saga example snippets
namespace App\Saga\Steps;
use JeromeJHipolito\Saga\Steps\AbstractSagaStep;
class CreateOrderStep extends AbstractSagaStep
{
public function execute(array $data): mixed
{
// Create the order
$order = Order::create([
'user_id' => $data['user_id'],
'total' => $data['total'],
]);
return ['order_id' => $order->id];
}
public function rollback(mixed $result, array $data): void
{
// Rollback: Delete the created order
if (isset($result['order_id'])) {
Order::find($result['order_id'])?->delete();
}
}
}
namespace App\Jobs;
use App\Saga\Steps\CreateOrderStep;
use App\Saga\Steps\ReserveInventoryStep;
use App\Saga\Steps\ProcessPaymentStep;
use JeromeJHipolito\Saga\Traits\UsesSaga;
class ProcessOrderJob implements ShouldQueue
{
use UsesSaga;
public function handle(): void
{
$data = [
'user_id' => $this->userId,
'items' => $this->items,
'total' => $this->total,
];
// Initialize the saga
$saga = $this->initializeSaga($data);
// Add steps
$saga->addStep(new CreateOrderStep())
->addStep(new ReserveInventoryStep())
->addStep(new ProcessPaymentStep());
// Execute - if any step fails, previous steps are rolled back
$this->executeSaga($data);
}
}
// Find an existing transaction
$saga = SagaTransactionManager::findByTransactionId('order-123');
$saga->isCompleted(); // true if all steps succeeded
$saga->hasFailed(); // true if any step failed