Skip to content

Lesson 24 of 45 · Commands and Queries

Command-Query Separation (CQS)

Intermediate•
lesson•
November 2, 2026•
~11 min read

A method that cancels and answers

The rich domain model lesson ended with this CancelReservationCommandHandler:

PHP
<?php declare(strict_types=1); namespace App\Reservations; use App\Payments\Payments; use Illuminate\Contracts\Events\Dispatcher; use Psr\Clock\ClockInterface; final readonly class CancelReservationCommandHandler { public function __construct( private Reservations $reservations, private Payments $payments, private Dispatcher $events, private ClockInterface $clock, ) {} public function handle(CancelReservationCommand $command): void { $reservation = $this->reservations->withId($command->reservationId); $refundAmount = $reservation->cancel($command->reason, $this->clock->now()); $this->reservations->save($reservation); if (!$refundAmount->isZero()) { $this->payments->refund($reservation->paymentId(), $refundAmount); } $this->events->dispatch(new ReservationCancelled($command->reservationId)); } }

The cancel() call moves the reservation to Cancelled and hands back the money to refund. Tell, Don't Ask named that shape, a method that changes state and returns a value, and moved on. This lesson asks what it costs the caller.

The handler runs cancel(), then save(), then refund(). If the worker dies between save() and refund(), the reservation is Cancelled and nothing records how much was owed, because the amount only ever existed as a return value. The retry calls cancel() again and gets an exception, since the reservation is no longer Confirmed.

What the caller can assume

Tell, Don't Ask gave the rule: a method either changes state or returns a value. Martin Fowler's page on the principle states the benefit as a rule about the caller:

The really valuable idea in this principle is that it's extremely handy if you can clearly separate methods that change state from those that don't. This is because you can use queries in many situations with much more confidence, introducing them anywhere, changing their order. You have to be more careful with modifiers.

The test is one question: can I call this twice? A query can be called twice, by a retry, a double-click, a debug dump() or a second template that wants the same number, and nothing changes. A command cannot, unless someone made it safe on purpose. Fowler defines queries as methods that "do not change the observable state of the system", and he calls the other kind "modifiers". The caller never has to read the body to know which kind it is holding, if the names and return types tell the truth.

Queries that write

The violations I find most often in Laravel codebases are methods named like queries that write.

PHP
<?php declare(strict_types=1); namespace App\Booking; use App\Booking\Models\GuestModel; final class GuestDirectory { public function guestWithEmail(string $email, string $name): GuestModel { return GuestModel::firstOrCreate( ['email' => $email], ['name' => $name], ); } }

(GuestModel is an Eloquent model that isn't shown.) guestWithEmail() reads like a lookup. In the Laravel 13.x source, firstOrCreate() runs where($attributes)->first() and, when that finds nothing, calls createOrFirst(), which runs create() (Illuminate/Database/Eloquent/Builder.php). Two double-clicked requests can both pass the lookup and both insert, and only a unique index on email turns the second insert into a read. A caller who sees guestWithEmail() has no reason to guard it.

The fix is two methods, a query and a command:

PHP
<?php declare(strict_types=1); namespace App\Booking; use App\Booking\Models\GuestModel; final class GuestDirectory { public function existingGuestWithEmail(string $email): ?GuestModel { return GuestModel::query()->where('email', $email)->first(); } public function registerGuest(string $email, string $name): void { GuestModel::query()->create(['email' => $email, 'name' => $name]); } }

The caller that wants "find or create" says so with a check and a call, and a code review can see the write. (RegisterGuestCommand is a readonly class with email and name, and isn't shown.)

PHP
<?php declare(strict_types=1); namespace App\Booking; final readonly class RegisterGuestCommandHandler { public function __construct(private GuestDirectory $guests) {} public function handle(RegisterGuestCommand $command): void { if ($this->guests->existingGuestWithEmail($command->email) === null) { $this->guests->registerGuest($command->email, $command->name); } } }

The split doesn't fix the race: two requests can still both find nothing, so keep the unique index on email. The losing request then gets Laravel's UniqueConstraintViolationException, where firstOrCreate() would have read the existing guest.

Other forms of the same bug are a nextInvoiceNumber() that bumps a sequence on every call and a current() that touches last_viewed_at. An Eloquent relation that lazy-loads on first access is not one of them: it fetches and remembers, and nothing a caller can observe has changed.

Cache::remember() is the borderline case. In the 13.x source (Cache/Repository.php) it calls get(), runs your closure on a miss, and put()s the result. The cache changed, but the answer is the same either way, and Fowler's definition covers only the observable state of the system. A cached read counts as a query. A closure that increments a counter or sends a request does not, and wrapping it in remember() hides that.

Three ways out of cancel()

cancel() returns the refund because the handler needs the amount and cancel() was the one computing it. There are three ways to keep the amount without the mixed signature.

The first is to ask before telling. The Strategy pattern lesson built CancellationPolicy::refundFor(), a query: it takes a price, stay dates and a time and returns Money. The handler asks it, then calls a cancel() that returns void. Here Reservation is the plain class from the Domain Events lesson, with the paymentId() accessor from the rich domain model lesson and a cancel(string $reason, DateTimeImmutable $now): void that only changes the status.

PHP
<?php declare(strict_types=1); namespace App\Reservations; use App\Payments\Payments; use App\Reservations\Cancellation\CancellationPolicy; use Psr\Clock\ClockInterface; final readonly class CancelReservationCommandHandler { public function __construct( private Reservations $reservations, private CancellationPolicy $policy, private Payments $payments, private ClockInterface $clock, ) {} public function handle(CancelReservationCommand $command): void { $now = $this->clock->now(); $reservation = $this->reservations->withId($command->reservationId); $refund = $this->policy->refundFor($reservation->totalPrice, $reservation->stayDates, $now); $reservation->cancel($command->reason, $now); $this->reservations->save($reservation); if (!$refund->isZero()) { $this->payments->refund($reservation->paymentId(), $refund); } } }

The same $now goes to both calls, so the amount asked for is the amount that applies at the moment of cancelling. The refund rule now sits in a class that anyone can call to preview a price, and the "what would I get back?" screen needs no reservation to cancel.

The second is to put the amount on the event. The Domain Events lesson had Reservation record events as it changes. cancel() can do the same and carry the refund on ReservationCancelled, which replaces the one-field event the rich domain model lesson dispatched.

PHP
<?php declare(strict_types=1); namespace App\Reservations\Events; use App\Billing\Money; use App\Payments\PaymentId; use App\Reservations\ReservationId; use DateTimeImmutable; final readonly class ReservationCancelled { public function __construct( public ReservationId $reservationId, public PaymentId $paymentId, public Money $refundAmount, public DateTimeImmutable $cancelledAt, ) {} }
PHP
<?php declare(strict_types=1); namespace App\Reservations; use App\Billing\Money; use App\Booking\GuestId; use App\Booking\RoomId; use App\Payments\PaymentId; use App\Reservations\Cancellation\CancellationPolicy; use App\Reservations\Events\ReservationCancelled; use App\Reservations\Exceptions\CannotCancelReservation; 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 readonly PaymentId $paymentId, private ReservationStatus $status, ) {} public function canCancel(DateTimeImmutable $now): bool { return $this->status === ReservationStatus::Confirmed && $this->stayDates->checkIn > $now; } public function cancel(string $reason, DateTimeImmutable $now, CancellationPolicy $policy): void { if (!$this->canCancel($now)) { throw new CannotCancelReservation($this->id); } $this->status = ReservationStatus::Cancelled; $this->recordedEvents[] = new ReservationCancelled( reservationId: $this->id, paymentId: $this->paymentId, refundAmount: $policy->refundFor($this->totalPrice, $this->stayDates, $now), cancelledAt: $now, ); } /** @return list<object> */ public function releaseEvents(): array { $events = $this->recordedEvents; $this->recordedEvents = []; return $events; } }

This trimmed version does not store the reason. The handler takes the shape it had in the Domain Events lesson: load, cancel() with the CancellationPolicy it receives in its constructor, save(), then dispatch whatever releaseEvents() returns. A listener on ReservationCancelled reads refundAmount and calls Payments::refund(). The refund is now a reaction to a fact, so it can be queued, retried and logged like the other reactions to domain events. The cost is that the refund no longer happens in the request, and a caller that must show "refunded" on the same screen has to wait for the listener.

The third is to keep the return value on purpose. Tell, Don't Ask left expire() returning the payment to refund, and that was a choice. It is a reasonable one when the value is a by-product that only exists at the moment of the change, the method guards against a second call, and you accept that callers must treat it as a modifier. cancel() passes the last two conditions and fails the first, because the refund can be computed before or after.

Creating things

A create has the same pull toward returning something. Reservation::request() calls ReservationId::next() inside itself, so the handler that creates a reservation is the only code that knows the new id, and the controller needs it for the redirect to /reservations/{id}. Either the handler returns it, or the controller reads the database afterwards to find what was made. The way out is to call ReservationId::next() in the caller and put the id on the command. The command below leaves out the special requests to stay short:

PHP
<?php declare(strict_types=1); namespace App\Reservations; use App\Booking\GuestCount; use App\Booking\GuestId; use App\Booking\RoomId; use App\Pricing\RatePlanCode; final readonly class RequestReservationCommand { public function __construct( public ReservationId $reservationId, public GuestId $guestId, public RoomId $roomId, public DateRange $stayDates, public GuestCount $guestCount, public RatePlanCode $ratePlanCode, ) {} }

The controller makes the id, sends the command, and redirects with the id it already holds:

PHP
<?php declare(strict_types=1); namespace App\Http\Controllers; use App\Http\Requests\RequestReservationRequest; use App\Reservations\RequestReservationCommand; use App\Reservations\RequestReservationCommandHandler; use App\Reservations\RequestReservationData; use App\Reservations\ReservationId; use Illuminate\Http\RedirectResponse; final class RequestReservationController { public function __invoke( RequestReservationRequest $request, RequestReservationCommandHandler $handler, ): RedirectResponse { $data = RequestReservationData::fromRequest($request); $reservationId = ReservationId::next(); $handler->handle(new RequestReservationCommand( reservationId: $reservationId, guestId: $data->guestId, roomId: $data->roomId, stayDates: $data->stayDates, guestCount: $data->guestCount, ratePlanCode: $data->ratePlanCode, )); return new RedirectResponse('/reservations/' . $reservationId->value); } }

Reservation::request() gains a first parameter, ReservationId $id, and passes it to the constructor instead of calling ReservationId::next(). The handler works out the price from the rate plan, calls request() and saves; its handle() returns void, and it isn't shown. A queued job that retries carries the same command and the same id, so a unique key on the id stops it from creating two reservations. A double-submitted form is two requests with two ids, so it still makes two reservations.

Tests split the same way

A query test asserts the return value, and calling it twice shows it is safe. A command test asserts the state change or the recorded events.

PHP
<?php declare(strict_types=1); namespace Tests\Unit\Reservations; use App\Billing\Currency; use App\Billing\Money; use App\Booking\GuestId; use App\Booking\RoomId; use App\Payments\PaymentId; use App\Reservations\Cancellation\CancellationPolicy; use App\Reservations\DateRange; use App\Reservations\Events\ReservationCancelled; use App\Reservations\Reservation; use App\Reservations\ReservationId; use App\Reservations\ReservationStatus; use Carbon\CarbonImmutable; use DateTimeImmutable; use PHPUnit\Framework\TestCase; final class ReservationCancellationTest extends TestCase { public function test_can_cancel_gives_the_same_answer_every_time(): void { $reservation = $this->confirmedReservation(); $now = new DateTimeImmutable('2026-05-20'); $this->assertTrue($reservation->canCancel($now)); $this->assertTrue($reservation->canCancel($now)); $this->assertSame([], $reservation->releaseEvents()); } public function test_cancel_records_the_refund_on_the_event(): void { $reservation = $this->confirmedReservation(); $policy = new class implements CancellationPolicy { public function refundFor(Money $totalPrice, DateRange $stayDates, DateTimeImmutable $now): Money { return $totalPrice; } }; $reservation->cancel('Change of plans', new DateTimeImmutable('2026-05-20'), $policy); $events = $reservation->releaseEvents(); $this->assertCount(1, $events); $this->assertInstanceOf(ReservationCancelled::class, $events[0]); $this->assertSame(20000, $events[0]->refundAmount->amountInCents); $this->assertFalse($reservation->canCancel(new DateTimeImmutable('2026-05-20'))); } private function confirmedReservation(): Reservation { return new Reservation( id: ReservationId::next(), guestId: GuestId::next(), roomId: new RoomId(14), stayDates: new DateRange( CarbonImmutable::parse('2026-06-01'), CarbonImmutable::parse('2026-06-03'), ), totalPrice: Money::fromCents(20000, Currency::usd()), paymentId: PaymentId::next(), status: ReservationStatus::Confirmed, ); } }

The same sorting applies one level up: a handler either changes the system and returns nothing, or answers a question and changes nothing. The next lesson builds the command side, and the one after builds the query side.

Pitfalls

A void return does not make a command safe to repeat. CQS limits what a method may return, not whether you can call it twice. The second cancel() throws CannotCancelReservation, and a retrying queue worker has to know that. Idempotency, where a second identical call has no further effect, is a separate property, and a command has it only if you build it in. For cancelling, give Reservation a query, isCancelled(): bool, that returns $this->status === ReservationStatus::Cancelled. The ask-before-telling handler from above returns early when it answers true:

PHP
<?php declare(strict_types=1); namespace App\Reservations; use App\Payments\Payments; use App\Reservations\Cancellation\CancellationPolicy; use Psr\Clock\ClockInterface; final readonly class CancelReservationCommandHandler { public function __construct( private Reservations $reservations, private CancellationPolicy $policy, private Payments $payments, private ClockInterface $clock, ) {} public function handle(CancelReservationCommand $command): void { $now = $this->clock->now(); $reservation = $this->reservations->withId($command->reservationId); if ($reservation->isCancelled()) { return; } $refund = $this->policy->refundFor($reservation->totalPrice, $reservation->stayDates, $now); $reservation->cancel($command->reason, $now); $this->reservations->save($reservation); if (!$refund->isZero()) { $this->payments->refund($reservation->paymentId(), $refund); } } }

A retried job then loads the cancelled reservation and stops before cancel() can throw. The early return also skips the refund after a crash between save() and the refund, or between save() and the event dispatch in the event version. Storing the refund or the event in the same transaction as the reservation fixes that, and a later course in this series covers it. The refund needs the same care: a refund row keyed by the reservation id, with a unique index, can't be recorded twice.

A check in the caller is advice, not protection. if ($reservation->canCancel($now)) { $reservation->cancel(...); } works only for callers that remember the if. Keep the guard inside cancel(), as above, so a caller that skips the check still gets an exception. Neither check stops two requests that load the same reservation at the same moment: both see Confirmed and both cancel. That race needs a lock or a version column. A version column is a counter that each update checks and increases, so the second of two racing writes fails.

Not every mixed method deserves a split. Fowler follows the principle when he can and breaks it for a stack pop: "I'm prepared to break it to get my pop." Popping a queue item or taking the next number from a database sequence are the same case. Name them like modifiers (pop, takeNext), document that they are, and keep them out of anything that gets retried blindly.

The one thing to remember

Before a caller reads a method's body, the name and return type should say whether the method changes anything. Put the write behind a command name, and keep any answer the caller needs behind a query it can repeat.

Course Content