Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Broadway Saga Laravel Package

broadway/broadway-saga

Broadway Saga adds saga/process manager support to the Broadway event-sourcing framework. Coordinate long-running business workflows across bounded contexts, reacting to domain events and dispatching commands to drive eventual consistency in CQRS/ES applications.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require broadway/broadway-saga
    

    Ensure broadway/broadway is also installed (required dependency).

  2. Register the Service Provider Add to config/app.php under providers:

    Broadway\Saga\SagaServiceProvider::class,
    
  3. Publish Configuration

    php artisan vendor:publish --provider="Broadway\Saga\SagaServiceProvider"
    

    Config file: config/broadway-saga.php.

  4. Define a Saga Create a class implementing Broadway\Saga\Saga:

    use Broadway\Saga\Saga;
    
    class OrderSaga implements Saga
    {
        public function __invoke()
        {
            // Saga logic here
        }
    }
    
  5. First Use Case: Trigger a Saga Use the SagaManager to start a saga:

    $sagaManager = app(SagaManager::class);
    $saga = $sagaManager->create(OrderSaga::class);
    $sagaManager->start($saga);
    

Where to Look First

  • Documentation: Broadway Saga Docs (if available; may require inferring from source).
  • Source Code:
    • src/Saga.php (interface definition).
    • src/SagaManager.php (core logic for saga orchestration).
    • src/Event/SagaStarted.php (event triggers).
  • Config File: config/broadway-saga.php (adjust retry policies, event dispatching, etc.).

Implementation Patterns

Workflow: Saga Orchestration

  1. Define Saga Steps Break saga logic into discrete steps (e.g., validateOrder, chargePayment, fulfillOrder):

    class OrderSaga implements Saga
    {
        public function __invoke()
        {
            $this->validateOrder();
            $this->chargePayment();
            $this->fulfillOrder();
        }
    
        private function validateOrder() { /* ... */ }
        private function chargePayment() { /* ... */ }
        private function fulfillOrder() { /* ... */ }
    }
    
  2. Handle Failures with Compensating Transactions Implement CompensatingTransaction for rollback logic:

    use Broadway\Saga\CompensatingTransaction;
    
    class ChargePaymentCompensation implements CompensatingTransaction
    {
        public function __invoke() { /* Refund logic */ }
    }
    
    // In saga:
    $this->chargePaymentWithCompensation(
        fn() => $this->chargePayment(),
        ChargePaymentCompensation::class
    );
    
  3. Event-Driven Triggers Use Broadway events to kick off sagas:

    // In an event subscriber:
    public function handle(OrderPlaced $event)
    {
        $sagaManager = app(SagaManager::class);
        $saga = $sagaManager->create(OrderSaga::class, ['orderId' => $event->orderId]);
        $sagaManager->start($saga);
    }
    

Integration Tips

  1. Leverage Broadway’s Event Store Store saga state in the event store for replayability:

    $sagaManager->setEventStore($eventStore); // Inject in provider
    
  2. Dependency Injection Bind saga dependencies in the service provider:

    $this->app->bind(OrderSaga::class, function ($app) {
        return new OrderSaga(
            $app->make(PaymentGateway::class),
            $app->make(OrderRepository::class)
        );
    });
    
  3. Testing Sagas Use SagaTestCase (if provided) or mock the SagaManager:

    $sagaManager = Mockery::mock(SagaManager::class);
    $sagaManager->shouldReceive('start')->once();
    
  4. Retry Policies Configure retries in config/broadway-saga.php:

    'retry_policy' => [
        'max_attempts' => 3,
        'delay' => 100, // ms
        'multiplier' => 2,
    ],
    

Gotchas and Tips

Pitfalls

  1. State Management

    • Issue: Sagas may lose state if not persisted properly.
    • Fix: Ensure all saga steps are idempotent and use Broadway’s event sourcing to reconstruct state.
  2. Circular Dependencies

    • Issue: Sagas triggering other sagas can create deadlocks.
    • Fix: Design sagas to be stateless or use a saga hierarchy with clear boundaries.
  3. Event Ordering

    • Issue: Out-of-order events can break saga logic.
    • Fix: Use event versioning or saga IDs to enforce ordering.
  4. Compensation Gaps

    • Issue: Missing compensating transactions leave the system in an inconsistent state.
    • Fix: Test compensation paths thoroughly and log failures.

Debugging

  1. Enable Saga Logging Add to config/broadway-saga.php:

    'logging' => [
        'enabled' => true,
        'channel' => 'single',
    ],
    
  2. Inspect Saga State Query the event store for saga events:

    php artisan tinker
    >>> $eventStore->load('saga-id');
    
  3. Common Exceptions

    • SagaAlreadyStartedException: Saga was already in progress. Fix: Use saga IDs to avoid duplicates.
    • CompensationFailedException: Compensating transaction failed. Fix: Implement retry logic or alerting.

Extension Points

  1. Custom Saga States Extend Broadway\Saga\SagaState to add metadata:

    class CustomSagaState extends SagaState
    {
        public $customField;
    }
    
  2. Event Dispatching Override SagaManager to dispatch custom events:

    $sagaManager->setEventDispatcher($customDispatcher);
    
  3. Saga Factories Create factories for complex saga initialization:

    $saga = app(SagaFactory::class)->create(OrderSaga::class, $data);
    
  4. Middleware for Sagas Add middleware to sagas (e.g., logging, auth):

    $sagaManager->addMiddleware(new LogSagaMiddleware());
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
besmartand-pro/php-quality-config
sentix/ai-chatbot
terminal42/code-quality-tools
codifyo/ts-generator-bundle
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity