Skip to content

Event-Driven Architecture

Domain events communicate state changes across the application. Events decouple components and enable reactive side effects without tight coupling.

Core Concept

Domain events are immutable objects published after successful operations. They represent facts about what happened in the business domain.

Characteristics:

  • Immutable (readonly classes)
  • Past tense naming (BookCreatedEvent, not CreateBookEvent)
  • Self-contained with all necessary data

Publishing Events

Events are published from command handlers after successful operations:

$this->bookRepository->save($book);
$this->eventBus->dispatch(new BookCreatedEvent($book));

Subscribing to Events

Event listeners are mapped to events in configuration:

// config/events.php
return [
    BookCreatedEvent::class => [
        BookEventHandler::class,
    ],
];

Handling Events

Event listeners react to events for side effects:

public function __invoke(object $event): void
{
    $this->logger->info('Book created', ['id' => $event->book->id()]);
}

Benefits

Decoupling

Publishers and listeners don't know about each other. New listeners can be added without modifying existing code.

Side Effects

Handle cross-cutting concerns reactively: logging, notifications, cache invalidation, audit trails.

Best Practices

  • Use past tense naming for events
  • Keep listeners focused on single responsibilities
  • Listeners handle side effects, not core business logic
  • Include all necessary information in event data

See Also