Skip to content

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

The Query Bus

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

The same summary, hundreds of times

The Queries and Query Handlers lesson built the booking detail page: ReservationSummaryController calls ReservationSummaryQueryHandler, which reads one row with two joins into a ReservationSummary. Front desk staff keep that page open and reload it all day. Most reloads ask for a reservation that hasn't changed since the last one.

This time the job is to cache those answers. The handler is the wrong home for it: caching has nothing to do with which columns a booking page needs, and the next query handler would need the same code. The previous lesson solved the same problem for commands with a bus and a pipe.

What a query bus is

A query bus takes a query object, runs the one handler mapped to its class, and returns the handler's answer. That return value is the difference. A command bus returns nothing; a query bus exists to answer.

PHP
<?php declare(strict_types=1); namespace App\Framework\Bus; interface QueryBus { public function ask(object $query): mixed; }

The method is called ask() so a call site reads as a question, and so nobody confuses it with the command bus's dispatch().

A second dispatcher, not the command bus

Laravel's dispatcher already returns the handler's result: dispatchNow() returns whatever the pipeline returns. So the adapter looks like the command bus adapter, with a return:

PHP
<?php declare(strict_types=1); namespace App\Framework\Bus; use Illuminate\Contracts\Bus\Dispatcher; final readonly class LaravelQueryBus implements QueryBus { public function __construct(private Dispatcher $dispatcher) {} public function ask(object $query): mixed { return $this->dispatcher->dispatchNow($query); } }

The dispatcher it receives must not be the shared one. The previous lesson showed that the application's dispatcher is one object, and that its pipes wrap every command and every queued job. Mapping queries into it would send every read through the command pipes. So the query bus gets its own Illuminate\Bus\Dispatcher instance, with its own map and its own pipes. A small provider builds it once:

PHP
<?php declare(strict_types=1); namespace App\Providers; use App\Framework\Bus\CacheQueryResult; use App\Framework\Bus\LaravelQueryBus; use App\Framework\Bus\QueryBus; use App\Reservations\ReservationSummaryQuery; use App\Reservations\ReservationSummaryQueryHandler; use Illuminate\Bus\Dispatcher; use Illuminate\Contracts\Foundation\Application; use Illuminate\Support\ServiceProvider; final class QueryBusServiceProvider extends ServiceProvider { public function register(): void { $this->app->singleton(QueryBus::class, function (Application $app): QueryBus { $dispatcher = new Dispatcher($app); $dispatcher->map([ ReservationSummaryQuery::class => ReservationSummaryQueryHandler::class, ]); $dispatcher->pipeThrough([CacheQueryResult::class]); return new LaravelQueryBus($dispatcher); }); } }

Each new query adds one line to the map() array. CacheQueryResult is the caching pipe, shown below. Register the provider in bootstrap/providers.php next to the others:

PHP
<?php declare(strict_types=1); return [ App\Providers\AppServiceProvider::class, App\Providers\QueryBusServiceProvider::class, App\Providers\ReservationEventServiceProvider::class, App\Providers\ReservationsServiceProvider::class, ];

Symfony needs no second dispatcher object, because each Messenger bus is its own service with its own middleware. Add a query.bus under buses: in config/packages/messenger.yaml and tag the handler with bus: query.bus. The adapter returns the answer with Messenger's HandleTrait: use HandleTrait; in the class, then return $this->handle($query); in ask(). HandleTrait throws unless exactly one handler ran. Its $messageBus property isn't readonly, so the adapter is final but not readonly.

The controller asks

The controller asks the bus instead of calling the handler:

PHP
<?php declare(strict_types=1); namespace App\Http\Controllers; use App\Framework\Bus\QueryBus; use App\Reservations\ReservationId; use App\Reservations\ReservationSummary; use App\Reservations\ReservationSummaryQuery; use Illuminate\Contracts\View\View; final class ReservationSummaryController { public function __invoke(string $reservationId, QueryBus $queries): View { $summary = $queries->ask(new ReservationSummaryQuery(new ReservationId($reservationId))); assert($summary instanceof ReservationSummary); return view('reservations.summary', ['summary' => $summary]); } }

The assert() line is the price of the bus. The query handler returned a ReservationSummary, and the IDE knew it. ask() returns mixed, so the type is gone until the controller states it again. assert() narrows the type for PHPStan and the IDE, and it fails loudly in development and tests. Whether it runs in production depends on zend.assertions: php.ini-production sets it to -1, which skips assertions, but PHP's built-in default is 1, and the official Docker images ship without a php.ini. Check yours.

One cache for every read

A decorator would be the other way to add a cache, but the query handlers are final readonly classes with no interface, so there is nothing to put a decorator in front of. The pipe wraps every handler from the outside instead.

Not every query should be cached, so the query says whether it can be and under which key. A small interface carries that:

PHP
<?php declare(strict_types=1); namespace App\Framework\Bus; interface CacheableQuery { public function cacheKey(): string; public function cacheSeconds(): int; }

The interface lives in App\Framework\Bus, and the reservations module imports it on purpose, the same way its handlers import EventDispatcher from App\Framework\Events. ReservationSummaryQuery implements it. The key holds everything the answer depends on, which here is only the reservation id:

PHP
<?php declare(strict_types=1); namespace App\Reservations; use App\Framework\Bus\CacheableQuery; final readonly class ReservationSummaryQuery implements CacheableQuery { public function __construct( public ReservationId $reservationId, ) {} public function cacheKey(): string { return 'reservation-summary.' . $this->reservationId->value; } public function cacheSeconds(): int { return 60; } }

The pipe caches what the rest of the chain returns, and lets every other query through untouched. It uses remember(), which command-query separation called the borderline case that still counts as a query: the cache changes, the answer doesn't.

PHP
<?php declare(strict_types=1); namespace App\Framework\Bus; use Closure; use Illuminate\Contracts\Cache\Repository; final readonly class CacheQueryResult { public function __construct(private Repository $cache) {} public function handle(object $query, Closure $next): mixed { if (!$query instanceof CacheableQuery) { return $next($query); } return $this->cache->remember( $query->cacheKey(), $query->cacheSeconds(), fn (): mixed => $next($query), ); } }

In Symfony the pipe is a Messenger middleware around CacheInterface::get(), which, like remember(), runs a closure on a miss and saves what it returns. The answer travels in a HandledStamp on the envelope, and HandleTrait needs exactly one. On a miss, return the envelope the rest of the chain returned. On a hit, add new HandledStamp($result, self::class) yourself. The middleware, in src/Framework/Bus/CacheQueryResult.php:

PHP
<?php declare(strict_types=1); namespace App\Framework\Bus; use Symfony\Component\Messenger\Envelope; use Symfony\Component\Messenger\Middleware\MiddlewareInterface; use Symfony\Component\Messenger\Middleware\StackInterface; use Symfony\Component\Messenger\Stamp\HandledStamp; use Symfony\Contracts\Cache\CacheInterface; use Symfony\Contracts\Cache\ItemInterface; final readonly class CacheQueryResult implements MiddlewareInterface { public function __construct(private CacheInterface $cache) {} public function handle(Envelope $envelope, StackInterface $stack): Envelope { $query = $envelope->getMessage(); if (!$query instanceof CacheableQuery) { return $stack->next()->handle($envelope, $stack); } $handled = null; $result = $this->cache->get( $query->cacheKey(), function (ItemInterface $item) use ($query, $envelope, $stack, &$handled): mixed { $item->expiresAfter($query->cacheSeconds()); $handled = $stack->next()->handle($envelope, $stack); return $handled->last(HandledStamp::class)?->getResult(); }, ); return $handled ?? $envelope->with(new HandledStamp($result, self::class)); } }

A handler that throws leaves nothing in the cache. Symfony Cache also rejects the characters {}()/\@: in a key, which is why the key above uses a dot.

A file, database or Redis store serializes what it stores, and Laravel 13's config/cache.php ships with 'serializable_classes' => false. With that setting no class instance comes back: the second read returns a __PHP_Incomplete_Class instead of a ReservationSummary, and the controller's assert() fails. The comment above the setting gives the reason: it prevents "gadget chain attacks if your APP_KEY is leaked". Unserializing data an attacker wrote can build any class in your app and run its code, and the allow-list limits that to the classes you name. So list the classes a cached answer is built from, including the ones nested inside it, such as Currency inside Money. Add this key to the array in config/cache.php:

PHP
<?php use App\Billing\Currency; use App\Billing\Money; use App\Reservations\ReservationId; use App\Reservations\ReservationStatus; use App\Reservations\ReservationSummary; return [ // The other keys stay as Laravel 13 ships them. 'serializable_classes' => [ ReservationSummary::class, ReservationId::class, Money::class, Currency::class, ReservationStatus::class, DateTimeImmutable::class, ], ];

Each new cached query adds its DTO and everything inside it. A class left off the list breaks the read: a Money whose Currency isn't listed fails with a TypeError.

Symfony Cache has no such allow-list. Its DefaultMarshaller calls unserialize() with allowed_classes set to true, so the summary comes back with nothing to configure, and the gadget chain risk stays. Treat write access to the cache store like write access to the database.

A test proves the handler runs once for two questions and that the answer survives the cache. It needs no framework boot and no database: a plain container, a cache store that serializes values the way a file or Redis store does, with the same allow-list, and a handler that counts its calls. The handler is bound in the container under a name, which is what map() stores:

PHP
<?php declare(strict_types=1); namespace Tests\Unit\Framework\Bus; use App\Billing\Currency; use App\Billing\Money; use App\Framework\Bus\CacheQueryResult; use App\Framework\Bus\LaravelQueryBus; use App\Reservations\ReservationId; use App\Reservations\ReservationStatus; use App\Reservations\ReservationSummary; use App\Reservations\ReservationSummaryQuery; use DateTimeImmutable; use Illuminate\Bus\Dispatcher; use Illuminate\Cache\ArrayStore; use Illuminate\Cache\Repository; use Illuminate\Container\Container; use PHPUnit\Framework\TestCase; final class CacheQueryResultTest extends TestCase { public function test_a_cacheable_query_runs_its_handler_once(): void { $handler = new class { public int $calls = 0; public function handle(ReservationSummaryQuery $query): ReservationSummary { $this->calls++; return new ReservationSummary( reservationId: $query->reservationId, guestName: 'Ana Petrovska', roomNumber: '214', checkIn: new DateTimeImmutable('2026-05-06'), checkOut: new DateTimeImmutable('2026-05-09'), status: ReservationStatus::Confirmed, totalPrice: Money::fromCents(42000, Currency::usd()), ); } }; $container = new Container(); $container->instance('summary-handler', $handler); $cache = new Repository(new ArrayStore(serializesValues: true, serializableClasses: [ ReservationSummary::class, ReservationId::class, Money::class, Currency::class, ReservationStatus::class, DateTimeImmutable::class, ])); $dispatcher = new Dispatcher($container); $dispatcher->map([ReservationSummaryQuery::class => 'summary-handler']); $dispatcher->pipeThrough([new CacheQueryResult($cache)]); $queries = new LaravelQueryBus($dispatcher); $query = new ReservationSummaryQuery(ReservationId::next()); $first = $queries->ask($query); $second = $queries->ask($query); $this->assertInstanceOf(ReservationSummary::class, $second); $this->assertEquals($first, $second); $this->assertSame(1, $handler->calls); } }

The test's allow-list is a copy of the config's, so keep the two lists in step.

A Symfony version of the test builds a MessageBus by hand from the caching middleware and a HandleMessageMiddleware with a HandlersLocator. Give it a FilesystemAdapter: an ArrayAdapter keeps a deep clone instead of a serialized string, so it never runs the round trip the test is there to prove.

How wrong a cached answer may be

A cached answer is a copy, and the copy goes stale the moment the reservation changes. Check a guest out, reload the page within the minute, and the summary still says CheckedIn.

Two ways to live with that. The first is to pick cacheSeconds() per query as the longest time that page may be wrong, and say it out loud: sixty seconds is fine for a page staff reload, and wrong for the screen the guest pays on. The second is to delete the key when the reservation changes. Reservation::checkOut() already records GuestCheckedOut and the check-out handler dispatches it, so a listener can call forget(), or delete() on Symfony's CacheInterface, with the same key: (new ReservationSummaryQuery($event->reservationId))->cacheKey(). The next lesson covers the listeners that react to those events.

A summary that shows different fields to a manager and to front desk staff needs the role in the key, or the first viewer's answer is served to everyone. The query then has to carry the role as a property, so cacheKey() can include it.

When it earns its place

The query bus earns its place when many reads need the same wrapper: caching, a permission check, a log line for slow reads. Each is one pipe. List them in the order they should run, because pipeThrough() runs the first pipe in the list first: a permission pipe goes before the cache pipe, or a cached answer reaches a caller who isn't allowed to see it. Messenger reads a bus's middleware list in the same order, and wraps it in its own middleware: stamps, dispatch_after_current_bus and failure handling before yours, send_message and handle_message after (FrameworkExtension.php in Symfony 8.1).

For one page with no wrapper, calling the handler directly is better. It keeps the return type, the IDE follows it to the handler, and there is no assert().

The one thing to remember

A query bus returns the handler's answer and keeps its own map and pipes, apart from the command bus. Use it when every read needs the same wrapper, and give each cached query a key that holds everything its answer depends on.

Course Content

Sign in to track your progress