Lesson 28 of 45 · Commands, Queries and Events on a Bus
The Command Bus
Three callers that name the handler
The Command Pattern lesson ended with three callers for one use case. CheckOutGuestController, CheckOutGuestArtisanCommand and CheckOutGuestJob each build a CheckOutGuestCommand and call CheckOutGuestCommandHandler::handle() themselves.
Then a new requirement arrives: log every command with how long it took, so the slow ones show up. The handler is the obvious place, but that lesson listed four earlier command handlers and built a fifth, and more are coming. Each would get the same timer and the same log call, and the next handler someone writes would forget them.
A command bus gives that code one home. It sits between the callers and the handlers, so anything that must happen around every handler happens in the bus.
What a command bus is
A command bus takes a command object and runs the one handler registered for that command's class. The caller depends on the bus and the command, and never names the handler. The interface has the same single-method shape as EventDispatcher from the dependency injection lesson:
<?php
declare(strict_types=1);
namespace App\Framework\Bus;
interface CommandBus
{
public function dispatch(object $command): void;
}It returns void for the same reason the handlers do: a command changes state, and the caller already holds any id it needs.
Laravel already maps commands to handlers
Illuminate\Contracts\Bus\Dispatcher, the bus dispatcher that also runs queued jobs (not the events dispatcher), has a map() method that registers one handler class per command class. Its dispatchNow() builds the mapped handler from the container and calls handle() (Illuminate/Bus/Dispatcher.php in Laravel 13). The adapter passes the command through:
<?php
declare(strict_types=1);
namespace App\Framework\Bus;
use Illuminate\Contracts\Bus\Dispatcher;
final readonly class LaravelCommandBus implements CommandBus
{
public function __construct(private Dispatcher $dispatcher) {}
public function dispatch(object $command): void
{
$this->dispatcher->dispatchNow($command);
}
}The binding and the mapping go in the ReservationsServiceProvider from the dependency injection lesson. Laravel calls a provider's boot() method through the container, so the dispatcher can be injected there:
<?php
declare(strict_types=1);
namespace App\Providers;
use App\Framework\Bus\CommandBus;
use App\Framework\Bus\LaravelCommandBus;
use App\Framework\Events\EventDispatcher;
use App\Framework\Events\LaravelEventDispatcher;
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\Support\ServiceProvider;
use Psr\Clock\ClockInterface;
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, LaravelEventDispatcher::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,
]);
}
}Each new use case adds one line to that array.
In Symfony, Messenger does the mapping. The adapter wraps a Messenger bus instead of Laravel's dispatcher: its constructor takes #[Autowire(service: 'command.bus')] private MessageBusInterface $bus, and dispatch() calls $this->bus->dispatch($command). Each handler gets a messenger.message_handler tag in config/services.yaml with bus: command.bus, handles: set to the command class and method: handle, so the handler class stays as it is. One tag per use case replaces the line in the map() array, and php bin/console debug:messenger lists each command next to its handler.
Callers depend on the bus
The controller asks for the bus instead of the handler:
<?php
declare(strict_types=1);
namespace App\Http\Controllers;
use App\Framework\Bus\CommandBus;
use App\Reservations\CheckOutGuestCommand;
use App\Reservations\ReservationId;
use Illuminate\Http\Response;
final class CheckOutGuestController
{
public function __invoke(string $reservationId, CommandBus $bus): Response
{
$bus->dispatch(new CheckOutGuestCommand(new ReservationId($reservationId)));
return new Response('', Response::HTTP_NO_CONTENT);
}
}The Artisan command and the job change the same way: CommandBus $bus in handle(), then $bus->dispatch(...).
A controller test no longer has to build the handler's dependencies. A fake bus records what it was given, the same way RecordingDispatcher from the dependency injection lesson records events:
<?php
declare(strict_types=1);
namespace App\Testing;
use App\Framework\Bus\CommandBus;
final class RecordingCommandBus implements CommandBus
{
/** @var list<object> */
public array $dispatched = [];
public function dispatch(object $command): void
{
$this->dispatched[] = $command;
}
}The test puts the fake in the container, posts to the check-out route, and checks which command came out. No reservation exists and no handler runs:
<?php
declare(strict_types=1);
namespace Tests\Feature\Reservations;
use App\Framework\Bus\CommandBus;
use App\Reservations\CheckOutGuestCommand;
use App\Reservations\ReservationId;
use App\Testing\RecordingCommandBus;
use Tests\TestCase;
final class CheckOutGuestControllerTest extends TestCase
{
public function test_it_dispatches_check_out_for_the_reservation_in_the_url(): void
{
$bus = new RecordingCommandBus();
$this->app->instance(CommandBus::class, $bus);
$reservationId = ReservationId::next();
$this->post('/reservations/' . $reservationId->value . '/check-out')->assertNoContent();
$this->assertEquals([new CheckOutGuestCommand($reservationId)], $bus->dispatched);
}
}The handler keeps its own test from the Command Pattern lesson.
A Symfony controller asks for the same CommandBus. In a WebTestCase, call static::createClient() first and then static::getContainer()->set(CommandBus::class, $bus): the test container replaces a private service only until something has built it.
One log line around every handler
Before a command reaches its handler, Laravel's dispatcher sends it through a list of pipes, and pipeThrough() sets that list. A pipe is a class with a handle() method that takes the command and a $next closure, the same shape as HTTP middleware. A later lesson covers that shape as the Pipeline pattern. This pipe times the rest of the chain and logs the result:
<?php
declare(strict_types=1);
namespace App\Framework\Bus;
use Closure;
use Psr\Log\LoggerInterface;
final readonly class LogCommandDuration
{
public function __construct(private LoggerInterface $logger) {}
public function handle(object $command, Closure $next): mixed
{
$startedAt = hrtime(true);
try {
return $next($command);
} finally {
$this->logger->info('Command finished', [
'command' => $command::class,
'milliseconds' => (hrtime(true) - $startedAt) / 1_000_000,
]);
}
}
}The finally block logs failed commands too. Register the pipe at the end of the provider's boot() method, after the map() call: $bus->pipeThrough([LogCommandDuration::class]);, with use App\Framework\Bus\LogCommandDuration; at the top of the file.
Every handler is now timed, and no handler mentions it.
Laravel's dispatcher is one shared object for the whole application, so the pipe reaches further than the reservations module. Queued jobs run through the same dispatchNow() when a worker picks them up (Illuminate/Queue/CallQueuedHandler.php), so queued listeners and queued mail get a log line too, with the job's class in the command field. And pipeThrough() replaces the list instead of adding to it: if a second provider calls it, the first provider's pipes silently stop running. Register every pipe in one call, in one provider.
In Symfony the pipe is a Messenger middleware. It implements MiddlewareInterface, and its handle(Envelope $envelope, StackInterface $stack): Envelope times $stack->next()->handle($envelope, $stack) the same way, in src/Framework/Bus/LogCommandDuration.php:
<?php
declare(strict_types=1);
namespace App\Framework\Bus;
use Psr\Log\LoggerInterface;
use Symfony\Component\Messenger\Envelope;
use Symfony\Component\Messenger\Middleware\MiddlewareInterface;
use Symfony\Component\Messenger\Middleware\StackInterface;
final readonly class LogCommandDuration implements MiddlewareInterface
{
public function __construct(private LoggerInterface $logger) {}
public function handle(Envelope $envelope, StackInterface $stack): Envelope
{
$startedAt = hrtime(true);
try {
return $stack->next()->handle($envelope, $stack);
} finally {
$this->logger->info('Command finished', [
'command' => $envelope->getMessage()::class,
'milliseconds' => (hrtime(true) - $startedAt) / 1_000_000,
]);
}
}
}It goes in config/packages/messenger.yaml as a middleware list under command.bus. That list adds to Messenger's own middleware instead of replacing it, and it belongs to that one bus, so another bus never runs it. It does see Symfony's mail, because the mailer dispatches on the default bus.
To queue a command, queue a job that dispatches it, like the CheckOutGuestJob above, whose handle() now takes the CommandBus. LaravelCommandBus calls dispatchNow(), which never queues, so a command class that implements ShouldQueue would still run inside the request. The worker runs that job through the same dispatcher, so the queued path writes two log lines: one for the job and one for the command. In Symfony a command is queued by routing its class to a transport under framework.messenger.routing, with no job class, and the middleware logs once when the command is sent and once when the worker handles it.
A transaction is another wrapper, and it doesn't belong here. A pipe that opens a transaction around the handler means the handler's events go out before the commit, so a synchronous listener can act on a reservation that is about to roll back. A later lesson keeps the transaction inside the handler, where the events can wait until the commit has happened. Messenger ships the same wrapper as its doctrine_transaction middleware, and the same advice applies.
One command, one handler
map() holds one handler per command class, and mapping a second handler for the same class replaces the first. That matches the rule of one handler per command. Messenger does the opposite: it runs every handler tagged for a message (HandleMessageMiddleware.php in Symfony 8.1). A second tag for CheckOutGuestCommand makes both handlers run on every dispatch, and dispatch() raises nothing. In Symfony the rule is yours to keep: one tag per command, and a look at debug:messenger when you add one.
When more things must happen after a guest checks out, such as charging the remaining balance and sending a receipt, they react to the fact that the guest checked out, so they sit outside the check-out command. Reservation::checkOut() records GuestCheckedOut, the handler dispatches it, and listeners react to it. The next lesson gives those reactions their own bus.
When it earns its place
The bus earns its place when something must wrap every handler: the timer above, an audit entry per command, a check that the current user may run it.
It doesn't earn its place for a handful of use cases with nothing to wrap. A direct call to the handler is shorter, an IDE jumps straight from the controller to the handler, and the stack trace has fewer frames.
Pitfalls
A command nobody mapped. If you dispatch a command that isn't in map(), Laravel's dispatcher falls back to calling __invoke() on the command itself, and you get ReflectionException: Method App\Reservations\CheckOutGuestCommand::__invoke() does not exist. The message never mentions the missing mapping. When you see it, check the provider first. Messenger's error is clearer: it throws NoHandlerForMessageException with No handler for message "App\Reservations\CheckOutGuestCommand"., so check the tag in config/services.yaml.
A bus that returns values. dispatchNow() returns whatever the handler returns, and Messenger's dispatch() returns an Envelope that carries it in a HandledStamp. Either makes it tempting to widen dispatch() to mixed and hand back the new reservation. Keep it void for the reasons the command-query separation lesson gave.
A handler exception arrives wrapped. On a synchronous Messenger bus, HandleMessageMiddleware catches each handler's exception and throws one HandlerFailedException after the loop. Nothing in the http-kernel, error-handler or framework-bundle packages mentions that class, so nothing unwraps it, and a catch (DomainException $e) around $bus->dispatch() in a controller never fires. Catch HandlerFailedException and read $e->getWrappedExceptions(DomainException::class), which returns the matching exceptions keyed by handler name (WrappedExceptionsTrait.php in Symfony 8.1). $e->getPrevious() holds the first one.
The one thing to remember
A command bus maps each command class to its one handler, so callers dispatch commands and never name handlers. Add it when something must wrap every handler, and register that wrapper once.