Skip to content

Lesson 30 of 45 · Commands, Queries and Events on a Bus

The Event Bus

Intermediate•
lesson•
November 4, 2026•
~8 min read

The third bus is already running

The last two lessons put a bus in front of commands and in front of queries. Events have had one since the dependency injection lesson: the EventDispatcher interface with its Laravel adapter, and the listeners the Domain Events lesson registered for ReservationConfirmed.

The three buses look alike from the caller's side, and they follow different rules:

Command bus

Query bus

Event bus

The message names

an instruction: CheckOutGuestCommand

a question: ReservationSummaryQuery

a fact, in the past tense: GuestCheckedOut

Handlers per message

exactly one

exactly one

none, one or many

Returns

nothing

the answer

nothing

Nobody registered

an error (the command bus's __invoke() message)

the same error

fine: nothing reacts yet

The last row matters most: a command with no handler is a bug. An event with no listeners is normal: the handler announces what happened whether or not anyone cares today.

In Symfony the event bus is a third Messenger bus. Its adapter dispatches each event with a stamp, $this->bus->dispatch($event, [new DispatchAfterCurrentBusStamp()]), on an event.bus configured with default_middleware: allow_no_handlers: true, so an event nobody handles passes through. With this chapter's three buses and a queue for the events, config/packages/messenger.yaml reads as follows (MESSENGER_TRANSPORT_DSN comes from .env):

YAML
framework: messenger: default_bus: command.bus buses: command.bus: middleware: - App\Framework\Bus\LogCommandDuration query.bus: middleware: - App\Framework\Bus\CacheQueryResult event.bus: default_middleware: allow_no_handlers: true transports: sync: 'sync://' async: '%env(MESSENGER_TRANSPORT_DSN)%' routing: App\Reservations\Events\ReservationConfirmed: async App\Reservations\Events\GuestCheckedOut: async

This lesson uses checking out. Reservation::checkOut() records GuestCheckedOut, and the check-out handler dispatches it after save(). The Command Pattern lesson didn't show the event, so here it is:

PHP
<?php declare(strict_types=1); namespace App\Reservations\Events; use App\Booking\GuestId; use App\Reservations\ReservationId; use DateTimeImmutable; final readonly class GuestCheckedOut { public function __construct( public ReservationId $reservationId, public GuestId $guestId, public DateTimeImmutable $checkedOutAt, ) {} }

Three things should happen when a guest checks out: charge whatever is left on the stay, forget the cached booking summary from the previous lesson, and email a receipt.

Listeners stay thin

Charging the balance is real business work. It loads the stay, works out what is still owed and talks to the payment provider. Written inside a listener, that work has no command, can't be called from anywhere else, and skips the pipes the Command Bus lesson put around every handler.

So the listener does one thing: it turns the fact into a command and dispatches it.

PHP
<?php declare(strict_types=1); namespace App\Billing; use App\Reservations\ReservationId; final readonly class ChargeStayBalanceCommand { public function __construct( public ReservationId $reservationId, ) {} }
PHP
<?php declare(strict_types=1); namespace App\Billing\Listeners; use App\Billing\ChargeStayBalanceCommand; use App\Framework\Bus\CommandBus; use App\Reservations\Events\GuestCheckedOut; use Illuminate\Contracts\Queue\ShouldQueueAfterCommit; final readonly class ChargeStayBalanceOnCheckOut implements ShouldQueueAfterCommit { public function __construct(private CommandBus $commands) {} public function handle(GuestCheckedOut $event): void { $this->commands->dispatch(new ChargeStayBalanceCommand($event->reservationId)); } }

ChargeStayBalanceCommandHandler is a handler like CheckOutGuestCommandHandler, mapped in the provider shown further down, and not shown here. It has its own test, the logging pipe times it, and a front desk button can dispatch the same command when a charge has to be retried by hand. The listener is queued and waits for the commit, for the reasons the Domain Events lesson gave: it calls a payment provider, and it must not run for a check-out that rolled back.

In Symfony the listener is the same class without implements ShouldQueueAfterCommit. Routing GuestCheckedOut to an async transport in messenger.yaml queues it. The stamp holds the event until the command bus has finished, which is after the handler's own commit, and drops it if the handler throws. Routing picks a transport for a whole message, so all three listeners run in the worker. When one of them fails, the retry runs only that one.

Reactions that are safe to run twice

The Domain Events lesson warned that a queued listener can run twice. Each of these listeners answers that differently.

Forgetting the cached summary is safe by nature. Deleting a key that is already gone does nothing, so this listener can run any number of times:

PHP
<?php declare(strict_types=1); namespace App\Reservations\Listeners; use App\Reservations\Events\GuestCheckedOut; use App\Reservations\ReservationSummaryQuery; use Illuminate\Contracts\Cache\Repository; final readonly class ForgetReservationSummary { public function __construct(private Repository $cache) {} public function handle(GuestCheckedOut $event): void { $this->cache->forget((new ReservationSummaryQuery($event->reservationId))->cacheKey()); } }

Sending a receipt is not safe: run it twice and the guest gets two emails. The listener needs a record that it already sent one, and the database can keep that record safely. Assume a sent_receipts table whose primary key is reservation_id. insertOrIgnore() returns the number of rows it inserted, so a second run inserts nothing and stops:

PHP
<?php declare(strict_types=1); namespace App\Notifications\Listeners; use App\Reservations\Events\GuestCheckedOut; use App\Reservations\Mail\CheckOutReceiptEmail; use Illuminate\Contracts\Mail\Mailer; use Illuminate\Contracts\Queue\ShouldQueueAfterCommit; use Illuminate\Database\ConnectionInterface; final readonly class SendCheckOutReceipt implements ShouldQueueAfterCommit { public function __construct( private ConnectionInterface $database, private Mailer $mailer, ) {} public function handle(GuestCheckedOut $event): void { $inserted = $this->database->table('sent_receipts')->insertOrIgnore([ 'reservation_id' => $event->reservationId->value, ]); if ($inserted === 0) { return; } $this->mailer->send(new CheckOutReceiptEmail($event->reservationId)); } }

(CheckOutReceiptEmail looks up the recipient from the reservation id, the same way ReservationConfirmedEmail does, and isn't shown.)

insertOrIgnore() works on MySQL, SQLite and PostgreSQL; SQL Server's grammar in Laravel throws instead. Doctrine DBAL has no insert-or-ignore: the Symfony version calls $connection->insert('sent_receipts', [...]) and returns from a catch (UniqueConstraintViolationException). On MySQL it becomes INSERT IGNORE, which also turns other errors into warnings instead of exceptions, so a bad value also returns 0, and this listener treats it as already sent. The DBAL catch swallows only duplicate keys.

The order of the two steps is a choice, and it has a cost. Insert first, as above, and a crash or a failed send after the insert means the receipt never goes out, because the retry finds the row and stops: at most once. Send first and record afterwards, and a crash between them sends it again on the retry: at least once. A missing receipt can be resent by hand; a double charge can't be taken back as easily, which is why ChargeStayBalanceCommandHandler records each charge in a row keyed by the reservation id under a unique index, and sends the reservation id to the payment provider as its idempotency key, the value a provider like Stripe uses to recognise a repeated request. A second run can neither record nor take a second charge.

All three listeners go into the ReservationEventServiceProvider, next to the ones for ReservationConfirmed:

PHP
<?php declare(strict_types=1); namespace App\Providers; use App\Audit\Listeners\RecordReservationConfirmed; use App\Billing\Listeners\ChargeStayBalanceOnCheckOut; use App\Notifications\Listeners\SendCheckOutReceipt; use App\Notifications\Listeners\SendReservationConfirmationEmail; use App\Reporting\Listeners\UpdateOccupancyStatistics; use App\Reservations\Events\GuestCheckedOut; use App\Reservations\Events\ReservationConfirmed; use App\Reservations\Listeners\ForgetReservationSummary; 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); Event::listen(GuestCheckedOut::class, ChargeStayBalanceOnCheckOut::class); Event::listen(GuestCheckedOut::class, ForgetReservationSummary::class); Event::listen(GuestCheckedOut::class, SendCheckOutReceipt::class); } }

In Symfony each listener gets a messenger.message_handler tag in config/services.yaml with bus: event.bus and the event class in handles:, one tag per listener. ForgetReservationSummary calls delete() on Symfony's CacheInterface, which does nothing for a missing key, like forget().

One log line around every event

The Command Bus lesson logged every command in a pipe. The event side has no pipe list, but it has the interface, and a decorator wraps it:

PHP
<?php declare(strict_types=1); namespace App\Framework\Events; use Psr\Log\LoggerInterface; final readonly class LoggingEventDispatcher implements EventDispatcher { public function __construct( private EventDispatcher $inner, private LoggerInterface $logger, ) {} public function dispatch(object $event): void { $this->logger->info('Event dispatched', ['event' => $event::class]); $this->inner->dispatch($event); } }

The binding changes from the plain adapter to the decorator around it. This is the ReservationsServiceProvider from the Command Bus lesson with that one binding changed and the charge handler mapped:

PHP
<?php declare(strict_types=1); namespace App\Providers; use App\Billing\ChargeStayBalanceCommand; use App\Billing\ChargeStayBalanceCommandHandler; use App\Framework\Bus\CommandBus; use App\Framework\Bus\LaravelCommandBus; use App\Framework\Bus\LogCommandDuration; use App\Framework\Events\EventDispatcher; use App\Framework\Events\LaravelEventDispatcher; use App\Framework\Events\LoggingEventDispatcher; use App\Reservations\CheckOutGuestCommand; use App\Reservations\CheckOutGuestCommandHandler; use App\Reservations\Infrastructure\EloquentReservations; use App\Reservations\Infrastructure\QueryBuilderReservationSummaries; use App\Reservations\Reservations; use App\Reservations\ReservationSummaries; use App\Support\SystemClock; use Illuminate\Contracts\Bus\Dispatcher; use Illuminate\Contracts\Foundation\Application; use Illuminate\Support\ServiceProvider; use Psr\Clock\ClockInterface; use Psr\Log\LoggerInterface; final class ReservationsServiceProvider extends ServiceProvider { public function register(): void { $this->app->bind(Reservations::class, EloquentReservations::class); $this->app->bind(ReservationSummaries::class, QueryBuilderReservationSummaries::class); $this->app->bind(EventDispatcher::class, fn (Application $app): EventDispatcher => new LoggingEventDispatcher( $app->make(LaravelEventDispatcher::class), $app->make(LoggerInterface::class), )); $this->app->bind(ClockInterface::class, SystemClock::class); $this->app->bind(CommandBus::class, LaravelCommandBus::class); } public function boot(Dispatcher $bus): void { $bus->map([ CheckOutGuestCommand::class => CheckOutGuestCommandHandler::class, ChargeStayBalanceCommand::class => ChargeStayBalanceCommandHandler::class, ]); $bus->pipeThrough([LogCommandDuration::class]); } }

Only events that go through the interface get the log line. A package that calls Laravel's Event::dispatch() directly goes around it, which is one more reason for application code to dispatch through EventDispatcher and never through the facade.

In Symfony, alias EventDispatcher to LoggingEventDispatcher in config/services.yaml and set its $inner argument to the Messenger adapter. Without that argument, autowiring resolves EventDispatcher back to the decorator itself, a circular reference.

What the bus doesn't promise

The bus doesn't promise delivery. The handler saves the reservation and then dispatches its events. If the process dies between the two, the reservation is checked out and GuestCheckedOut never reaches the bus: no charge, no receipt, and a summary that stays cached for up to 60 seconds. This is the crash from the command-query separation lesson, on the event side. The fix is to store the events in the same transaction as the reservation and publish them from there, which a later course in this series covers. Until then, know which reactions you can't afford to lose, and give them a way to be found and rerun, such as a nightly check for checked-out stays with no charge.

In Symfony the window is wider. Between the command handler returning and the send, the event waits in the in-memory queue of DispatchAfterCurrentBusMiddleware. A crash anywhere in that window loses it, and so does a failed write to the transport.

The one thing to remember

Keep each listener on an event bus thin, let it dispatch a command when there is real work, and make it safe to run twice. The bus doesn't promise delivery, so decide which reactions you can't afford to lose.

Course Content

Sign in to track your progress