Lesson 14 of 22 · Architecture and Code Organization
Laravel Command Bus for a Use Case Without a Shape
The previous lesson ended with the module in place and RequestReservation doing what it did before the move: it takes a guest id and an array, and it sends the confirmation mail itself.
The use case gets a formal shape
RequestReservation::handle(int $guestId, array $attributes) worked. Now is a good moment to give it the shape every use case in the codebase will share, because the form and the channel import both call it.
The caller's intent and its data become one object, the command. It is a plain, immutable value (readonly, so nothing can change its fields once it is built): a name that says what the caller wants and the fields the handler needs.
<?php
declare(strict_types=1);
namespace App\Reservations\RequestReservation;
final readonly class RequestReservationCommand
{
/**
* @param array<string, mixed> $attributes
*/
public function __construct(
public int $guestId,
public array $attributes,
) {
}
}The class that carries the command out is the handler. It has one public method, handle(), that takes the command.
<?php
declare(strict_types=1);
namespace App\Reservations\RequestReservation;
use App\Guests\Guest\Guest;
use App\Pricing\NightlyRatePricing;
use App\Reservations\Reservation\Reservation;
use App\Reservations\Reservation\ReservationStatus;
use App\Rooms\Room\Room;
use Carbon\CarbonImmutable;
use Illuminate\Contracts\Events\Dispatcher;
use Illuminate\Support\Str;
final readonly class RequestReservationCommandHandler
{
public function __construct(
private NightlyRatePricing $pricing,
private Dispatcher $events,
) {
}
public function handle(RequestReservationCommand $command): Reservation
{
$guest = Guest::query()->findOrFail($command->guestId);
$room = Room::query()->with('roomType')->findOrFail($command->attributes['room_id']);
$checkIn = CarbonImmutable::parse($command->attributes['check_in']);
$checkOut = CarbonImmutable::parse($command->attributes['check_out']);
$reservation = Reservation::query()->create([
'guest_id' => $guest->id,
'status' => ReservationStatus::CONFIRMED,
'confirmed_at' => CarbonImmutable::now(),
'confirmation_code' => Str::upper(Str::random(8)),
'total_cents' => $this->pricing->totalCents($room->roomType, $checkIn, $checkOut),
...$command->attributes,
]);
$this->events->dispatch(new ReservationConfirmed($reservation->id, $guest->id));
return $reservation;
}
}The handler also stops naming the request's keys: it spreads $command->attributes into create() after the values it computes. A later lesson comes back to that.
This handler replaces App\Reservations\RequestReservation\RequestReservation, so that file is deleted. The RequestReservationTest goes with it, because it asserted on a mail the handler no longer sends. A later lesson writes its replacement, which checks the row and the event.
The handler's job is the state change. Sending an email is something that happens because a reservation was confirmed, so the handler announces the fact and something else reacts. The announcement is an event, a past-tense name plus the ids a reaction would need.
<?php
declare(strict_types=1);
namespace App\Reservations\RequestReservation;
final readonly class ReservationConfirmed
{
public function __construct(
public int $reservationId,
public int $guestId,
) {
}
}The reaction is a listener with the mailer injected. It loads what it needs by id. ReservationConfirmation implements ShouldQueue, so the request that created the reservation does not wait for an SMTP round trip, and a mail failure fails the queued job instead of the request. That is the channel import from the start of the course: with a real queue connection configured, a mail server timeout on row 300 no longer stops the loop after the reservation is saved. The listener itself runs in the request; only the mail goes to the queue.
<?php
declare(strict_types=1);
namespace App\Reservations;
use App\Reservations\RequestReservation\ReservationConfirmed;
use App\Reservations\Reservation\Reservation;
use Illuminate\Contracts\Mail\Mailer;
final readonly class SendReservationConfirmation
{
public function __construct(
private Mailer $mailer,
) {
}
public function handle(ReservationConfirmed $event): void
{
$reservation = Reservation::query()
->with(['guest', 'room'])
->findOrFail($event->reservationId);
$this->mailer
->to($reservation->guest->email)
->send(new ReservationConfirmation($reservation));
}
}The ReservationConfirmation mailable is queued now:
<?php
declare(strict_types=1);
namespace App\Reservations;
use App\Reservations\Reservation\Reservation;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Mail\Mailable;
use Illuminate\Mail\Mailables\Content;
use Illuminate\Mail\Mailables\Envelope;
use Illuminate\Queue\SerializesModels;
final class ReservationConfirmation extends Mailable implements ShouldQueue
{
use Queueable;
use SerializesModels;
public function __construct(public Reservation $reservation)
{
}
public function envelope(): Envelope
{
return new Envelope(
subject: 'Your reservation '.$this->reservation->confirmation_code,
);
}
public function content(): Content
{
return new Content(markdown: 'mail.reservation-confirmation');
}
}Wiring the command to its handler
The controller does not call the handler. It builds the command and hands it to Laravel's command bus, Illuminate\Contracts\Bus\Dispatcher, which looks up the handler for that command class and returns whatever handle() returns. The caller never names the handler, so a job or an import can dispatch the same command without knowing which class runs it.
<?php
declare(strict_types=1);
namespace App\Reservations\RequestReservation;
use App\Reservations\ReservationRequest;
use Illuminate\Contracts\Bus\Dispatcher;
use Illuminate\Http\JsonResponse;
final readonly class RequestReservationController
{
public function __construct(
private Dispatcher $bus,
) {
}
public function __invoke(ReservationRequest $request): JsonResponse
{
$reservation = $this->bus->dispatch(new RequestReservationCommand(
guestId: (int) $request->user()->guest_id,
attributes: $request->validated(),
));
return (new RequestReservationResource($reservation))->response()->setStatusCode(201);
}
}The bus needs to be told which handler goes with which command, and the module's service provider is where that mapping lives, next to the routes and the listener registration. A provider is wiring, not use-case code, so facades are fine here.
<?php
declare(strict_types=1);
namespace App\Reservations;
use App\Reservations\RequestReservation\RequestReservationCommand;
use App\Reservations\RequestReservation\RequestReservationCommandHandler;
use App\Reservations\RequestReservation\ReservationConfirmed;
use Illuminate\Support\Facades\Bus;
use Illuminate\Support\Facades\Event;
use Illuminate\Support\ServiceProvider;
final class ReservationsServiceProvider extends ServiceProvider
{
public function boot(): void
{
Bus::map([
RequestReservationCommand::class => RequestReservationCommandHandler::class,
]);
Event::listen(ReservationConfirmed::class, SendReservationConfirmation::class);
$this->loadRoutesFrom(__DIR__.'/reservations-routes.php');
}
}Without a mapping, the bus falls back to calling a handle() method on the command object itself, which puts the work back inside the data that describes it.
The import controller builds the same command from the channel manager's rows.
<?php
declare(strict_types=1);
namespace App\Reservations\ImportChannelReservations;
use App\Guests\Guest\Guest;
use App\Reservations\RequestReservation\RequestReservationCommand;
use Illuminate\Contracts\Bus\Dispatcher;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
final readonly class ImportChannelReservationsController
{
public function __construct(
private Dispatcher $bus,
) {
}
public function __invoke(Request $request): JsonResponse
{
$rows = $request->input('reservations', []);
foreach ($rows as $row) {
$guest = Guest::query()->firstOrCreate(
['email' => $row['guest']['email']],
['name' => $row['guest']['name'], 'phone' => $row['guest']['phone'] ?? null],
);
$this->bus->dispatch(new RequestReservationCommand(
guestId: $guest->id,
attributes: [
'room_id' => $row['room_id'],
'check_in' => $row['arrival'],
'check_out' => $row['departure'],
'adults' => $row['adults'],
'children' => $row['children'],
],
));
}
return new JsonResponse(['imported' => count($rows)], 200);
}
}After this lesson the files for the use case sit together:
app/Reservations/
ReservationsServiceProvider.php
SendReservationConfirmation.php
ReservationConfirmation.php
RequestReservation/
RequestReservationCommand.php
RequestReservationCommandHandler.php
RequestReservationController.php
RequestReservationResource.php
ReservationConfirmed.phpThe one thing to remember
Give each use case a command, a handler, and an explicit mapping between them.