Skip to content

Lesson 22 of 45 · Behavior and Variation

Domain Events

Intermediate•
lesson•
October 31, 2026•
~13 min read

The handler that keeps growing

ConfirmReservationCommandHandler started small. Payment comes back authorized, the handler tells the reservation to confirm itself, and saves it. (ConfirmReservationCommand carries a reservationId and a paymentAuthorization. Reservation is trimmed to what this lesson reads: id, guestId, roomId, stayDates and totalPrice are public readonly properties.)

PHP
<?php declare(strict_types=1); namespace App\Reservations; use Psr\Clock\ClockInterface; final readonly class ConfirmReservationCommandHandler { public function __construct( private Reservations $reservations, private ClockInterface $clock, ) {} public function handle(ConfirmReservationCommand $command): void { $reservation = $this->reservations->withId($command->reservationId); $reservation->confirm($command->paymentAuthorization, $this->clock->now()); $this->reservations->save($reservation); } }

Three lines of real work, kept clean because the confirmation rule lives on the entity, the move the Tell, Don't Ask lesson made for cancelling.

Then marketing wants a confirmation email, and someone adds a mailer call. Compliance wants every confirmation written to an audit trail, and someone adds an insert. The operations dashboard wants live occupancy numbers, and someone adds an update to a statistics table. After enough asks like that, the handler looks like this:

PHP
<?php declare(strict_types=1); namespace App\Reservations; use App\Reservations\Mail\ReservationConfirmedEmail; use Illuminate\Contracts\Mail\Mailer; use Illuminate\Support\Facades\DB; use Psr\Clock\ClockInterface; final readonly class ConfirmReservationCommandHandler { public function __construct( private Reservations $reservations, private ClockInterface $clock, private Mailer $mailer, ) {} public function handle(ConfirmReservationCommand $command): void { $reservation = $this->reservations->withId($command->reservationId); $reservation->confirm($command->paymentAuthorization, $this->clock->now()); $this->reservations->save($reservation); $this->mailer->send(new ReservationConfirmedEmail($reservation->id)); DB::table('audit_log')->insert([ 'event' => 'reservation.confirmed', 'reservation_id' => $reservation->id->value, 'occurred_at' => $this->clock->now(), ]); DB::table('occupancy_stats') ->where('room_id', $reservation->roomId->value) ->increment('confirmed_reservations'); } }

Every line does something a real stakeholder asked for. The problem is where the lines live. ConfirmReservationCommandHandler now has four reasons to change: the confirmation rule itself, the email copy, the audit schema, and the reporting table. A handler test that only wants to check that the reservation gets confirmed and saved has to construct a mailer double, stub the audit insert, and stub the stats update, or the test breaks for reasons that have nothing to do with confirmation.

Worse, the next side effect (a Slack notification, a loyalty-points award, a webhook to a channel manager) means opening this same file again and adding a fifth reason to change.

The fix is a seam. Michael Feathers introduced the term in Working Effectively with Legacy Code (2004): a seam is a place where you can change behavior without editing the code at that place. A handler that announces what happened, instead of calling each reaction itself, has one. Adding a reaction changes what happens on confirmation without editing the handler.

What an event actually is

The announcement is a domain event: a record that something happened in the business, named in business words. ReservationConfirmed is a fact: a reservation was confirmed, at a specific time, with a specific payment authorization. It already happened. Nothing that reacts to it can undo it or negotiate about it.

A domain event, as a PHP class, has a small, consistent shape:

  • Named in the past tense, for the business fact that occurred: ReservationConfirmed, not ConfirmReservation (that's the command) and not ReservationConfirmedEvent (the suffix is noise once the class lives in an Events namespace).

  • Immutable. Once constructed, its properties don't change. Something happened; the record of it doesn't get edited later.

  • Carries ids and plain values, never entities or Eloquent models. A listener that receives the Reservation itself can change it; an Eloquent model also lets it call save() or lazy-load unrelated relationships. An event that carries a ReservationId and a Money forces every listener to go fetch what it needs through its own repository, which keeps each listener's data access honest and makes the event safe to serialize onto a queue.

PHP
<?php declare(strict_types=1); namespace App\Reservations\Events; use App\Billing\Money; use App\Booking\GuestId; use App\Booking\RoomId; use App\Payments\PaymentId; use App\Reservations\DateRange; use App\Reservations\ReservationId; use DateTimeImmutable; final readonly class ReservationConfirmed { public function __construct( public ReservationId $reservationId, public GuestId $guestId, public RoomId $roomId, public DateRange $stayDates, public Money $totalPrice, public PaymentId $paymentId, public DateTimeImmutable $confirmedAt, ) {} }

The seam in code

The handler needs one new dependency to publish this event: the EventDispatcher interface from the Dependency Injection lesson. It has one method, dispatch(object $event): void, it is owned by application code, and a Laravel adapter sits behind it. That interface is the seam. The handler depends on it instead of depending on mailers, audit tables, and statistics tables directly.

PHP
<?php declare(strict_types=1); namespace App\Reservations; use App\Framework\Events\EventDispatcher; use App\Reservations\Events\ReservationConfirmed; use Psr\Clock\ClockInterface; final readonly class ConfirmReservationCommandHandler { public function __construct( private Reservations $reservations, private EventDispatcher $events, private ClockInterface $clock, ) {} public function handle(ConfirmReservationCommand $command): void { $now = $this->clock->now(); $reservation = $this->reservations->withId($command->reservationId); $reservation->confirm($command->paymentAuthorization, $now); $this->reservations->save($reservation); $this->events->dispatch(new ReservationConfirmed( reservationId: $reservation->id, guestId: $reservation->guestId, roomId: $reservation->roomId, stayDates: $reservation->stayDates, totalPrice: $reservation->totalPrice, paymentId: $command->paymentAuthorization->id, confirmedAt: $now, )); } }

The handler is back to three lines of real work plus one line announcing what happened. It no longer knows or cares that an email gets sent, an audit row gets written, or a statistics table gets updated. Those are somebody else's job.

The Observer pattern, by name

What just happened has a name from the Gang of Four catalog: the Observer pattern. A subject holds a list of observers that want to know when something happens to it. The subject doesn't know what the observers do with the notification, and the observers don't know about each other. They only share the event. Here the dispatcher sits between the code that announces and the listeners that react, which makes it closer to publish-subscribe, a variation on the same one-to-many idea.

Laravel's Event facade and the Dispatcher contract are one implementation: dispatch() notifies every listener registered for that event's class. Symfony's EventDispatcherInterface and its dispatch() method are the same idea with different vocabulary; Symfony calls the registered classes "listeners" too, and also supports "subscribers", classes that declare which events they listen to in one place. Strip the framework names away and both are the pattern Erich Gamma and the rest of the Gang of Four wrote up in 1994: one-to-many notification, decoupled at the interface.

Listeners: one job each

Every side effect that used to live inline in the handler becomes its own listener. Each one takes the event, does its one job, and returns.

PHP
<?php declare(strict_types=1); namespace App\Notifications\Listeners; use App\Reservations\Events\ReservationConfirmed; use App\Reservations\Mail\ReservationConfirmedEmail; use Illuminate\Contracts\Mail\Mailer; final readonly class SendReservationConfirmationEmail { public function __construct(private Mailer $mailer) {} public function handle(ReservationConfirmed $event): void { $this->mailer->send(new ReservationConfirmedEmail($event->reservationId)); } }
PHP
<?php declare(strict_types=1); namespace App\Audit\Listeners; use App\Audit\AuditEvent; use App\Audit\AuditLogger; use App\Reservations\Events\ReservationConfirmed; final readonly class RecordReservationConfirmed { public function __construct(private AuditLogger $auditLogger) {} public function handle(ReservationConfirmed $event): void { $this->auditLogger->record(AuditEvent::for( name: 'reservation.confirmed', subjectId: $event->reservationId->value, occurredAt: $event->confirmedAt, )); } }
PHP
<?php declare(strict_types=1); namespace App\Reporting\Listeners; use App\Reporting\OccupancyStatistics; use App\Reservations\Events\ReservationConfirmed; final readonly class UpdateOccupancyStatistics { public function __construct(private OccupancyStatistics $statistics) {} public function handle(ReservationConfirmed $event): void { $this->statistics->recordConfirmation($event->roomId); } }

(AuditLogger is the interface from the Null Object Pattern lesson. AuditEvent::for() and OccupancyStatistics are small classes of the app's own, not shown. ReservationConfirmedEmail looks up the recipient from the reservation id, as in the capstone lesson.)

Three classes, each in the module it actually belongs to: Notifications, Audit, Reporting. Each one has exactly one reason to change. A test for RecordReservationConfirmed doesn't need a mailer double, because it never sees one. Adding a fourth side effect, a Slack message when a suite is confirmed, means adding a fourth listener, not touching the other three or the handler.

By default, Laravel finds listeners on its own by scanning the application's Listeners directory (see Event Discovery in the Laravel 13.x events docs). These live in other modules, so a service provider registers them (list the provider in bootstrap/providers.php so Laravel loads it):

PHP
<?php declare(strict_types=1); namespace App\Providers; use App\Audit\Listeners\RecordReservationConfirmed; use App\Notifications\Listeners\SendReservationConfirmationEmail; use App\Reporting\Listeners\UpdateOccupancyStatistics; use App\Reservations\Events\ReservationConfirmed; use Illuminate\Support\Facades\Event; use Illuminate\Support\ServiceProvider; final class ReservationEventServiceProvider extends ServiceProvider { public function boot(): void { Event::listen(ReservationConfirmed::class, SendReservationConfirmationEmail::class); Event::listen(ReservationConfirmed::class, RecordReservationConfirmed::class); Event::listen(ReservationConfirmed::class, UpdateOccupancyStatistics::class); } }

Discovery can scan the modules instead: ->withEvents(discover: [__DIR__.'/../app/*/Listeners']) in bootstrap/app.php replaces the default path with a pattern that matches every module's Listeners folder. The provider has one advantage over that: the full list of reactions to ReservationConfirmed sits in one file you can read.

Synchronous or queued, and what changes

By default, a Laravel listener runs synchronously, in the same request, inside any database transaction that is open when the event is dispatched. That's fine for fast work like the audit insert above. Once a listener does something slow or unreliable (sending an email through a third-party API, calling an external channel manager), implementing a queue interface on the listener pushes it onto a queue instead. ShouldQueueAfterCommit extends ShouldQueue:

PHP
<?php declare(strict_types=1); namespace App\Notifications\Listeners; use App\Reservations\Events\ReservationConfirmed; use App\Reservations\Mail\ReservationConfirmedEmail; use Illuminate\Contracts\Mail\Mailer; use Illuminate\Contracts\Queue\ShouldQueueAfterCommit; final readonly class SendReservationConfirmationEmail implements ShouldQueueAfterCommit { public function __construct(private Mailer $mailer) {} public function handle(ReservationConfirmed $event): void { $this->mailer->send(new ReservationConfirmedEmail($event->reservationId)); } }

Two things change once a listener is queued. First, it runs later on a queue worker, not inside the request. Whether it also waits for the transaction depends on configuration. The after_commit option on a queue connection defaults to false, so with plain ShouldQueue a job dispatched inside a transaction can be picked up before the transaction commits and look for a reservation that isn't visible yet (Laravel 13.x queue docs, "Jobs & Database Transactions"). ShouldQueueAfterCommit, or after_commit set to true on the connection, makes the listener wait for the commit. If the transaction rolls back, the queued listener is discarded, so it never fires against a reservation that was not confirmed. A synchronous listener that already ran can't be un-run. Implementing ShouldHandleEventsAfterCommit makes a synchronous listener wait for the commit too.

Second, the event has to survive being serialized to the queue's storage and rebuilt later, which is the other reason events carry ids and value objects instead of Eloquent models. An id, looked up fresh by the listener, reflects the database as it is when the worker runs. Laravel's make:event stub adds the SerializesModels trait, which does the same for Eloquent models: it stores the model's id and fetches the model again on the worker. Ids do it without the trait and keep the event free of Eloquent. Symfony's equivalent is routing the message through Symfony Messenger with an async transport, which raises the same two consequences.

Recording the event on the entity

So far the handler builds the event itself, right after save(). A more disciplined shape has Reservation::confirm() record the event internally, as part of confirming, so the rule for producing the event lives next to the rule for confirming. (This Reservation is trimmed again, to what confirming needs.)

PHP
<?php declare(strict_types=1); namespace App\Reservations; use App\Billing\Money; use App\Booking\GuestId; use App\Booking\RoomId; use App\Payments\PaymentAuthorization; use App\Reservations\Events\ReservationConfirmed; use App\Reservations\Exceptions\CannotConfirmReservation; use DateTimeImmutable; final class Reservation { /** @var list<object> */ private array $recordedEvents = []; public function __construct( public readonly ReservationId $id, public readonly GuestId $guestId, public readonly RoomId $roomId, public readonly DateRange $stayDates, public readonly Money $totalPrice, private ReservationStatus $status, ) {} public function confirm(PaymentAuthorization $authorization, DateTimeImmutable $now): void { if ($this->status !== ReservationStatus::Pending) { throw new CannotConfirmReservation($this->id, $this->status); } $this->status = ReservationStatus::Confirmed; $this->recordedEvents[] = new ReservationConfirmed( reservationId: $this->id, guestId: $this->guestId, roomId: $this->roomId, stayDates: $this->stayDates, totalPrice: $this->totalPrice, paymentId: $authorization->id, confirmedAt: $now, ); } /** @return list<object> */ public function releaseEvents(): array { $events = $this->recordedEvents; $this->recordedEvents = []; return $events; } }

(CannotConfirmReservation is a named exception like CannotCancelReservation in the Tell, Don't Ask lesson, and isn't shown. The Exception Handling as Design lesson covers exceptions like these.)

With the entity recording its own events, the handler no longer builds one. It releases whatever the entity recorded and dispatches each event after save():

PHP
<?php declare(strict_types=1); namespace App\Reservations; use App\Framework\Events\EventDispatcher; use Psr\Clock\ClockInterface; final readonly class ConfirmReservationCommandHandler { public function __construct( private Reservations $reservations, private EventDispatcher $events, private ClockInterface $clock, ) {} public function handle(ConfirmReservationCommand $command): void { $reservation = $this->reservations->withId($command->reservationId); $reservation->confirm($command->paymentAuthorization, $this->clock->now()); $this->reservations->save($reservation); foreach ($reservation->releaseEvents() as $event) { $this->events->dispatch($event); } } }

The advantage is that the rule "confirming produces a ReservationConfirmed event" lives next to the rule "confirming requires these conditions", on the same class, instead of being something the handler has to remember to do correctly every time. The Event Bus lesson covers the event bus that routes these events to their listeners. Event sourcing treats the recorded events as the source of truth for the reservation's state rather than a side channel next to it.

When it earns its place

Events earn their place once one action has to trigger more than one thing that different parts of the system care about, and those things don't need to happen in lockstep with each other. ReservationConfirmed fanning out to notifications, audit, and reporting is the textbook case: three modules, three owners, none of which needs to know the others exist. Events also earn their place at the border between two areas of the codebase that each have their own model, where one needs to react to something that happened in the other without importing the other's models.

A single side effect that the caller genuinely needs to know succeeded or failed is a direct call. Capturing a payment as part of confirming a reservation, where the reservation must not be marked confirmed if the capture fails, wants a synchronous method call inside the same transaction, with a real return value or a real exception the handler can act on. Dispatching PaymentCaptureRequested and hoping a listener reacts in time turns a requirement into a race condition. If the calling code needs the result back to decide what to do next, use a method call.

Pitfalls

Listeners that call other listeners. If RecordReservationConfirmed calls SendReservationConfirmationEmail directly to make sure the email goes out first, the two listeners are coupled to each other's existence and order, which defeats the reason to use events. Work that must happen in a specific order, or must all succeed or fail together, belongs in the handler as a direct sequence of calls, not a chain of listeners.

Events used as commands in disguise. SendEmailEvent is a command wearing an event's clothes. It doesn't describe something that happened; it tells one specific listener what to do, and usually has exactly one listener. A name that describes an instruction rather than a fact wants a direct method call.

Listeners that throw and fail the caller. A synchronous listener's exception propagates, by default, back to whoever dispatched the event. If UpdateOccupancyStatistics throws because the reporting table is briefly locked, and nobody catches it, the whole ConfirmReservationCommandHandler::handle() call fails, and if the caller wrapped it in a transaction the confirmation rolls back too, for a reason unrelated to confirming a reservation. Side effects that can't be allowed to threaten the operation they react to should queue, or should catch and log their own failures instead of letting them bubble up.

Fan-out with no owner. Once enough listeners react to the same event, nobody remembers all of them exist, and someone changes a field one listener depended on without realizing it's in use. Before changing an event, run php artisan event:list --event=ReservationConfirmed to see every listener registered for it.

Treating the dispatcher as a link between services. Laravel's and Symfony's in-process dispatchers run within a single application. They aren't a substitute for a real message broker when two separately deployed services need to talk to each other. A broker such as SQS, RabbitMQ, or Kafka has its own delivery guarantees.

Forgetting queued listeners need idempotency. A queue can redeliver a job after a timeout even though the listener already ran. If UpdateOccupancyStatistics were queued, the counter it blindly increments could double-count on redelivery. Make the operation idempotent (insert one row per reservation id, ignoring duplicates, and count the rows, or check a processed-event id) or accept the risk explicitly.

The one thing to remember

When a handler is a short recipe followed by a lengthening list of things that happen to be true afterward (send this email, write this row, bump this counter), stop and ask whether those things are reactions to a fact rather than steps in the recipe. If they are, name the fact, dispatch it once, and let each reaction live as its own listener, in the module that owns it.

Course Content