Skip to content

Lesson 25 of 45 · Commands and Queries

The Command Pattern: Commands and Command Handlers

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

The classes you have been reading so far

CancelReservationCommandHandler in the rich domain model lesson. CheckInGuestCommandHandler in the dependency injection lesson. MarkNoShowsCommandHandler in the repository lesson. ConfirmReservationCommandHandler in the Domain Events lesson. Every one of them has the same shape: a small class with a constructor full of dependencies and one public method that carries out a use case. The Service Pattern lesson said "Application services are command handlers in this style" and moved on.

This lesson names the shape and says what belongs in it. The use case this time is checking a guest out of the hotel.

The command holds the input

A command is a plain object that says what the caller wants done and carries the data needed to do it. The name is an instruction in the imperative: CheckOutGuestCommand, not GuestCheckout and not CheckOutGuestData. The class is final readonly, its properties are value objects where a value object exists, and it has no methods.

PHP
<?php declare(strict_types=1); namespace App\Reservations; final readonly class CheckOutGuestCommand { public function __construct( public ReservationId $reservationId, ) {} }

This is the same idea as the DTO from the Data Transfer Objects lesson, with one difference in meaning. A DTO describes data that moves between layers. A command also says which use case should run, so the class name is part of the contract. CancelReservationCommand carries a ReservationId and a reason, and CheckOutGuestCommand carries only the ReservationId. Without the reason the two would hold the same data, and they would still be two commands.

The Gang of Four's Command pattern puts an execute() method on the command itself, and that method calls the object that does the work. Here the command only carries the input and a separate handler does the work, so the command stays a plain value you can queue, log or test.

The command does not decide anything. It doesn't check that the reservation is checked in, and it doesn't read the clock. Those belong to the entity and the handler.

The handler runs the use case

The handler has one public method, handle(), which takes the command. Its dependencies come in through the constructor. The body follows the order the earlier handlers followed: load the entity through the repository, tell it what to do, save it, and dispatch the events it recorded.

Reservation::checkOut(DateTimeImmutable $now) moves the status from CheckedIn to CheckedOut and records a GuestCheckedOut event. Neither the method nor the event is shown here, the same way checkIn() wasn't shown with CheckInGuestCommandHandler.

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

Read the body as a checklist. The rule "a guest can only check out of a checked-in reservation" is nowhere in it. It lives in Reservation::checkOut(), which throws when the status is wrong. The handler decides the order of the steps and nothing else. If you find an if about the business in a handler, it probably belongs on the entity.

The handler takes everything through its constructor, so a test builds it with the fakes from the dependency injection lesson and no framework. InMemoryReservations keeps reservations in an array (the test doubles lesson shows it in full), RecordingDispatcher keeps every event it is given, and FrozenClock answers a fixed time. The Reservation constructor is the one from the Domain Events lesson, and GuestCheckedOut lives in App\Reservations\Events next to ReservationConfirmed:

PHP
<?php declare(strict_types=1); namespace App\Reservations\Tests; use App\Billing\Currency; use App\Billing\Money; use App\Booking\GuestId; use App\Booking\RoomId; use App\Reservations\CheckOutGuestCommand; use App\Reservations\CheckOutGuestCommandHandler; use App\Reservations\DateRange; use App\Reservations\Events\GuestCheckedOut; use App\Reservations\Reservation; use App\Reservations\ReservationId; use App\Reservations\ReservationStatus; use App\Testing\FrozenClock; use App\Testing\InMemoryReservations; use App\Testing\RecordingDispatcher; use Carbon\CarbonImmutable; use PHPUnit\Framework\TestCase; use Throwable; final class CheckOutGuestCommandHandlerTest extends TestCase { public function test_checking_out_dispatches_guest_checked_out(): void { [$handler, $events, $reservationId] = $this->handlerWithReservationIn(ReservationStatus::CheckedIn); $handler->handle(new CheckOutGuestCommand($reservationId)); $this->assertCount(1, $events->dispatched); $this->assertInstanceOf(GuestCheckedOut::class, $events->dispatched[0]); } public function test_a_guest_who_never_checked_in_cannot_check_out(): void { [$handler, $events, $reservationId] = $this->handlerWithReservationIn(ReservationStatus::Confirmed); $thrown = null; try { $handler->handle(new CheckOutGuestCommand($reservationId)); } catch (Throwable $exception) { $thrown = $exception; } $this->assertNotNull($thrown); $this->assertSame([], $events->dispatched); } /** @return array{CheckOutGuestCommandHandler, RecordingDispatcher, ReservationId} */ private function handlerWithReservationIn(ReservationStatus $status): array { $reservationId = ReservationId::next(); $reservations = new InMemoryReservations(); $reservations->save(new Reservation( id: $reservationId, guestId: GuestId::next(), roomId: new RoomId(14), stayDates: new DateRange( CarbonImmutable::parse('2026-05-06'), CarbonImmutable::parse('2026-05-09'), ), totalPrice: Money::fromCents(42000, Currency::usd()), status: $status, )); $events = new RecordingDispatcher(); $handler = new CheckOutGuestCommandHandler( reservations: $reservations, events: $events, clock: new FrozenClock('2026-05-09 11:00'), ); return [$handler, $events, $reservationId]; } }

The second test catches Throwable because the exception checkOut() throws isn't shown here; once it has a name, the test should expect that class. Either way, a refused check-out dispatches nothing.

One handler, three callers

The handler knows nothing about HTTP, the console or the queue, so any of them can call it. Each caller turns its own input into a CheckOutGuestCommand and passes it in. All three examples below assume Laravel 13.

Route parameters reach a controller method by name, and the container fills in the handler. The route is Route::post('/reservations/{reservationId}/check-out', CheckOutGuestController::class).

PHP
<?php declare(strict_types=1); namespace App\Http\Controllers; use App\Reservations\CheckOutGuestCommand; use App\Reservations\CheckOutGuestCommandHandler; use App\Reservations\ReservationId; use Illuminate\Http\Response; final class CheckOutGuestController { public function __invoke(string $reservationId, CheckOutGuestCommandHandler $handler): Response { $handler->handle(new CheckOutGuestCommand(new ReservationId($reservationId))); return new Response('', Response::HTTP_NO_CONTENT); } }

An Artisan command gets the same handler through handle() method injection. Laravel calls the method through the container ($this->laravel->call([$this, $method]) in Illuminate\Console\Command), so type-hinted parameters are resolved for you. The Signature attribute is how Laravel 13's make:command stub declares the name and arguments; on older versions the same string goes in a $signature property.

PHP
<?php declare(strict_types=1); namespace App\Console\Commands; use App\Reservations\CheckOutGuestCommand; use App\Reservations\CheckOutGuestCommandHandler; use App\Reservations\ReservationId; use Illuminate\Console\Attributes\Description; use Illuminate\Console\Attributes\Signature; use Illuminate\Console\Command; #[Signature('reservations:check-out {reservationId}')] #[Description('Check a guest out of a reservation')] final class CheckOutGuestArtisanCommand extends Command { public function handle(CheckOutGuestCommandHandler $handler): int { $reservationId = new ReservationId((string) $this->argument('reservationId')); $handler->handle(new CheckOutGuestCommand($reservationId)); return self::SUCCESS; } }

The class is called CheckOutGuestArtisanCommand because CheckOutGuestCommand is taken. Laravel and this lesson both use "command" for different things: an Artisan command is a console entry point, and a command object is a use case's input.

A queued job works the same way. When a worker runs a job, Illuminate\Bus\Dispatcher::dispatchNow() calls $this->container->call([$command, 'handle']), so the job's handle() method can type-hint the handler too. The job stores the id and builds the command when it runs, so what goes onto the queue is one small value object and not a loaded reservation (the same reasoning as events carrying ids).

PHP
<?php declare(strict_types=1); namespace App\Reservations\Jobs; use App\Reservations\CheckOutGuestCommand; use App\Reservations\CheckOutGuestCommandHandler; use App\Reservations\ReservationId; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Foundation\Queue\Queueable; use Illuminate\Queue\Attributes\Tries; #[Tries(3)] final class CheckOutGuestJob implements ShouldQueue { use Queueable; public function __construct( public readonly ReservationId $reservationId, ) {} public function handle(CheckOutGuestCommandHandler $handler): void { $handler->handle(new CheckOutGuestCommand($this->reservationId)); } }

Dispatching it from anywhere is CheckOutGuestJob::dispatch($reservationId). The Dispatchable trait inside Queueable supplies that static method. Laravel attempts a job once by default, so #[Tries(3)] gives the job two more attempts before it lands in the failed_jobs table. A nightly process that checks out guests who forgot to leave can queue one job per reservation, and each job gets its own retries.

Return values

A handler returns nothing. CheckOutGuestCommandHandler::handle() is void, and so is every command handler in this course so far. That follows from command-query separation: a command changes state, so it doesn't also answer a question.

Creating something looks like the exception, because the caller usually wants the new id. Command-query separation removes the need: the caller generates the id with ReservationId::next() before sending the command, puts it in the command, and already holds it when the handler returns. If the caller needs data afterwards, it asks a query.

Why an object and not plain arguments

handle(ReservationId $reservationId) would work for this use case, and the next lesson says plain arguments are fine for a query with one caller. For commands the object pays for itself sooner. A use case that needs a second input, such as the reason that CancelReservationCommand carries next to its id, changes the command class and its constructor calls, and nothing in between. The command is also the one thing a queue, a log line or a test can hold as a single value: a log entry that says CheckOutGuestCommand with a reservation id is readable, and a list of positional arguments is not.

What each caller does when the handler fails

The handler throws when the rule is broken: ReservationNotFound from the repository, or the exception Reservation::checkOut() throws for a reservation that isn't checked in. It doesn't know what a failure means to its caller, and each caller decides. For the controller, Laravel's exception handling in bootstrap/app.php turns ReservationNotFound into a 404 and a wrong status into a 422, so the controller itself stays as shown. The Artisan command prints the message and returns self::FAILURE. The job lets the exception escape, so the worker retries it until its three attempts run out, or catches it and calls $this->fail() when a retry can't help. Keeping that choice out of the handler is what lets all three share it.

When it earns its place

A handler earns its place when a use case has more than one caller, or has more than one step, or both. Checking out has four steps (load, tell, save, dispatch) and three callers, so the handler removes three copies of the same sequence.

It doesn't earn its place on a settings screen where a form writes one row and nothing else reacts. $user->update($request->validated()) in the controller is fine there. No rule would live on an entity, no second caller exists, and a command with a handler would be two new classes that restate one line. Add the handler when the second caller or the second step appears.

Pitfalls

Handlers that call handlers. CheckOutGuestCommandHandler calling ChargeStayBalanceCommandHandler ties two use cases together, and a failure in the second leaves the first half-finished. Two use cases that must happen together are a third use case, or the second one reacts to an event. Code that both need goes on an entity or a domain service.

Commands that carry a Request or an Eloquent model. A command holding a FormRequest can only be built inside an HTTP request, which takes the Artisan command and the job away. A command holding an Eloquent model has already loaded the entity, so the handler's withId() call is dead weight and the queue has to serialize a model. Commands carry ids and value objects.

One handler doing two use cases. A ReservationCommandHandler with cancel(), checkIn() and checkOut() methods is ReservationService from the Service Pattern lesson with a new suffix. One handler, one command, one handle().

A bus is the next step

Right now the controller, the Artisan command and the job each name the handler class they call. A command bus puts a dispatcher between the caller and the handler: the caller hands over the command object and the bus finds the handler. That lets you add a log line or a timer around every handler in one place, and a later lesson builds one. Until you need that, calling the handler directly is shorter and easier to follow in a stack trace.

The one thing to remember

A use case is one command object with its input and one handler that loads, tells, saves and dispatches. Because the handler knows nothing about its caller, a controller, an Artisan command and a queued job can share it.

Course Content