Best Practices

Handle failures gracefully

Event handlers should never throw back into the dispatcher — other listeners must continue to run:

public function handle(object $event): void
{
    try {
        // Your logic
    } catch (\Throwable $e) {
        $this->logger->error('Handler failed', [
            'handler' => static::class,
            'event'   => get_class($event),
            'error'   => $e->getMessage(),
        ]);
        // Consider: queue for retry, alert, etc.
    }
}

Use idempotency

Webhooks may be delivered multiple times. Use payment-base’s idempotency table (oe_payments_idempotency) or your own marker store to deduplicate:

public function handle(object $event): void
{
    $eventId = $event->getContext()->get('eventId');

    if ($this->processedEvents->has($eventId)) {
        return; // Already processed
    }

    // Process event...

    $this->processedEvents->markProcessed($eventId);
}

Keep handlers fast

The dispatcher runs handlers synchronously inside the request that produced the event. For slow integrations (ERP exports, third-party APIs), queue the work and acknowledge fast:

public function handle(object $event): void
{
    $this->queue->push(new ERPExportJob(
        $event->getContext()->toArray(),
    ));
}

Bind to concrete event classes

Symfony’s EventDispatcher resolves listeners by exact dispatched class name, not by walking interfaces. If you want to react to “any contract terminated” you cannot bind to ContractTerminatedEventInterface — bind one listener each for ContractCancelledEvent, ContractExpiredEvent and ContractFailedEvent.

Test your handlers in isolation

Handlers are plain classes — instantiate them with mocks and assert the side effects:

class ERPOrderExportHandlerTest extends TestCase
{
    public function testExportsOrderOnPaymentCaptured(): void
    {
        $erpClient = $this->createMock(ERPApiClient::class);
        $erpClient->expects($this->once())
            ->method('createOrder')
            ->willReturn('ERP-12345');

        $handler = new ERPOrderExportHandler($erpClient, new NullLogger());

        $event = new PaymentCapturedEvent(new EventContext([
            'orderId'  => 'OXID-123',
            'amount'   => 99.99,
            'currency' => 'EUR',
        ]));

        $handler->handle($event);
    }
}