Lesson 45 of 45 · Putting It Together
Refactoring Legacy Code: The Course Capstone
What this lesson is for
You've read 44 lessons of patterns, principles, and habits. The danger of finishing a course like this one is that the patterns sit in your head as a list of nouns, with no story for how they fit together. This last lesson is the antidote: a single, sustained refactoring of a realistic example, applying the toolkit to actual code, with the trade-offs visible.
The example is a "create reservation" feature, taken from a small Laravel codebase. The starting code is realistic: it works, and it shows the typical signs of a feature that grew without being shaped.
The starting code
<?php
declare(strict_types=1);
namespace App\Http\Controllers;
use App\Reservations\Mail\ReservationConfirmation;
use Carbon\CarbonImmutable;
use Illuminate\Database\ConnectionInterface as Connection;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Contracts\Mail\Mailer;
use Illuminate\Routing\Controller;
use Psr\Log\LoggerInterface;
use Symfony\Component\Lock\LockFactory;
final class RequestReservationController extends Controller
{
public function __construct(
private Connection $db,
private Mailer $mailer,
private LockFactory $locks,
private LoggerInterface $logger,
) {}
public function __invoke(Request $request): JsonResponse
{
$data = $request->validate([
'room_id' => 'required|integer|exists:rooms,id',
'check_in' => 'required|date',
'check_out' => 'required|date|after:check_in',
'rate_plan_code' => 'nullable|string',
]);
$guestId = $request->user()->getAuthIdentifier();
$lock = $this->locks->createLock("room:{$data['room_id']}:slot:{$data['check_in']}");
if (!$lock->acquire()) {
return new JsonResponse(['error' => 'slot is being reserved'], 409);
}
try {
$room = $this->db->table('rooms')->find($data['room_id']);
$nights = $this->nightsBetween($data['check_in'], $data['check_out']);
if ($room->max_nights < $nights) {
return new JsonResponse(['error' => 'stay too long'], 422);
}
$existing = $this->db->table('reservations')
->where('room_id', $data['room_id'])
->where('check_in', '<', $data['check_out'])
->where('check_out', '>', $data['check_in'])
->exists();
if ($existing) {
return new JsonResponse(['error' => 'slot already booked'], 409);
}
$price = $room->nightly_rate * $nights;
if (!empty($data['rate_plan_code'])) {
$ratePlan = $this->db->table('rate_plans')->where('code', $data['rate_plan_code'])->first();
if ($ratePlan && $ratePlan->expires_at > now() && $ratePlan->uses_left > 0) {
$price = match ($ratePlan->type) {
'percent' => $price * (1 - $ratePlan->amount / 100),
'fixed' => max(0, $price - $ratePlan->amount),
};
$this->db->table('rate_plans')
->where('id', $ratePlan->id)
->decrement('uses_left');
}
}
$reservationId = $this->db->table('reservations')->insertGetId([
'room_id' => $data['room_id'],
'guest_id' => $guestId,
'check_in' => $data['check_in'],
'check_out' => $data['check_out'],
'price_cents' => (int) round($price * 100),
'created_at' => now(),
]);
$this->mailer->send(new ReservationConfirmation($reservationId));
$this->logger->info('reservation.created', ['id' => $reservationId, 'user' => $guestId]);
return new JsonResponse(['id' => $reservationId], 201);
} finally {
$lock->release();
}
}
private function nightsBetween(string $checkIn, string $checkOut): int
{
return (int) CarbonImmutable::parse($checkIn)->diffInDays(CarbonImmutable::parse($checkOut));
}
}The application already binds LockFactory in the container, which the refactored version keeps (step 10 shows the binding).
The smell inventory
Before doing anything, let's name what's wrong, in the language of the toolkit:
Framework coupling. The controller imports
Connection, calls$this->db->table(...), uses helpers likenow(), calls$request->user()->getAuthIdentifier().Fat controller. The action handles validation, locking, queries, business rules, persistence, side effects, and response shaping.
Primitive obsession. Money is a
float. IDs areint. Dates arestring.Anemic data. No domain object exists for "reservation"; the rules live in the controller.
Validation stuck at the edge. The rules live only in the controller; nothing inside protects the domain from bad input.
Missing seams. There is no DTO, command, handler or repository.
Shotgun side effects. The mailer, the logger, and the ratePlan decrement all live in the same method as the business logic.
Generic error responses.
return new JsonResponse(['error' => '...'], 4XX)repeated.
Step 1: Pin the current behavior
Before touching the controller, we write a characterization test for it: a feature test that hits the endpoint over HTTP and checks both the response and the row it wrote. It runs against the original controller above and has to pass before step 2.
<?php
declare(strict_types=1);
namespace Tests\Feature;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\DB;
use Tests\TestCase;
final class RequestReservationTest extends TestCase
{
use RefreshDatabase;
public function test_it_creates_a_reservation(): void
{
$user = User::factory()->create();
$roomId = DB::table('rooms')->insertGetId([
'nightly_rate' => 100,
'max_nights' => 14,
]);
$response = $this->actingAs($user)->postJson('/reservations', [
'room_id' => $roomId,
'check_in' => '2026-06-01',
'check_out' => '2026-06-03',
]);
$response->assertCreated();
$this->assertDatabaseHas('reservations', [
'room_id' => $roomId,
'guest_id' => $user->id,
'price_cents' => 20000,
]);
}
}Add whatever other not-null columns your rooms table has to the insert.
The test assumes the route is registered in routes/web.php as Route::post('/reservations', RequestReservationController::class)->middleware('auth');. After the UUID reservation id arrives in step 6, the test keeps passing only once the key migration for the reservations table (outside this lesson) has run.
Step 2: Extract input handling
First move: pull the validation out of the controller and into a Form Request, then carry the validated data inward as a typed DTO.
<?php
declare(strict_types=1);
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
final class RequestReservationRequest extends FormRequest
{
public function rules(): array
{
return [
'room_id' => ['required', 'integer', 'exists:rooms,id'],
'check_in' => ['required', 'date'],
'check_out' => ['required', 'date', 'after:check_in'],
'rate_plan_code' => ['nullable', 'string', 'regex:/^[A-Z0-9-]{4,32}$/'],
];
}
}The new regex rule is a deliberate change. The RatePlanCode value object in step 3 rejects malformed codes, and without the rule a malformed code would reach it and throw. The original silently ignored an unknown code, and still does for a well-formed code that matches no rate plan. The rule also rejects legacy codes that are lowercase or contain other characters, which the original's MySQL match (case-insensitive) accepted.
<?php
declare(strict_types=1);
namespace App\Reservations;
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 ?RatePlanCode $ratePlanCode,
) {}
}The command uses domain types where they exist (we'll define GuestId, RoomId, DateRange and RatePlanCode in a moment, and ReservationId in step 6). The controller's job becomes parsing the request into the command and handing it to the handler.
Step 3: Lift the primitives
The course's GuestId wraps a UUID string. This codebase's users table uses auto-increment ids, so GuestId wraps an int here, as RoomId already does.
<?php
declare(strict_types=1);
namespace App\Booking;
use InvalidArgumentException;
final readonly class RoomId
{
public function __construct(public int $value)
{
if ($value <= 0) {
throw new InvalidArgumentException('Room id must be positive');
}
}
}<?php
declare(strict_types=1);
namespace App\Booking;
use InvalidArgumentException;
final readonly class GuestId
{
public function __construct(public int $value)
{
if ($value <= 0) {
throw new InvalidArgumentException('Guest id must be positive');
}
}
}<?php
declare(strict_types=1);
namespace App\Pricing;
use InvalidArgumentException;
final readonly class RatePlanCode
{
public function __construct(public string $value)
{
if (!preg_match('/^[A-Z0-9-]{4,32}$/', $value)) {
throw new InvalidArgumentException("Invalid rate plan code: {$value}");
}
}
}<?php
declare(strict_types=1);
namespace App\Reservations;
use Carbon\CarbonImmutable;
use InvalidArgumentException;
final readonly class DateRange
{
public function __construct(
public CarbonImmutable $checkIn,
public CarbonImmutable $checkOut,
) {
if (!$checkOut->greaterThan($checkIn)) {
throw new InvalidArgumentException('DateRange must end after it starts');
}
}
public static function ofNights(CarbonImmutable $checkIn, int $nights): self
{
return new self($checkIn, $checkIn->addDays($nights));
}
public function nights(): int
{
return (int) $this->checkIn->diffInDays($this->checkOut);
}
public function overlaps(DateRange $other): bool
{
return $this->checkIn < $other->checkOut && $this->checkOut > $other->checkIn;
}
}Each of these value objects has its own validation. The "invalid rate plan" and "stay must check out after check-in" rules now live with the types they belong to. Anywhere these types appear in the codebase, the rules are guaranteed. nights() calls diffInDays on the earlier date, because Carbon 3 returns a negative number when the argument is earlier than the receiver.
This DateRange is trimmed to what this lesson needs (the Immutable Objects lesson shows the full class, including withCheckOut).
Money is the fifth primitive from the smell list. The refactor uses the Money class from the Value Objects and Named Constructors lessons, and the rate plan and price code below builds on it.
Step 4: Move to command and handler
<?php
declare(strict_types=1);
namespace App\Http\Controllers;
use App\Booking\GuestId;
use App\Booking\RoomId;
use App\Http\Requests\RequestReservationRequest;
use App\Pricing\RatePlanCode;
use App\Reservations\DateRange;
use App\Reservations\RequestReservationCommand;
use App\Reservations\RequestReservationCommandHandler;
use App\Reservations\ReservationId;
use Carbon\CarbonImmutable;
use Illuminate\Http\JsonResponse;
final readonly class RequestReservationController
{
public function __construct(
private RequestReservationCommandHandler $handler,
) {}
public function __invoke(RequestReservationRequest $request): JsonResponse
{
$reservationId = ReservationId::next();
$ratePlanCode = $request->validated('rate_plan_code');
$this->handler->handle(new RequestReservationCommand(
reservationId: $reservationId,
guestId: new GuestId((int) $request->user()->getAuthIdentifier()),
roomId: new RoomId((int) $request->validated('room_id')),
stayDates: new DateRange(
CarbonImmutable::parse($request->validated('check_in')),
CarbonImmutable::parse($request->validated('check_out')),
),
ratePlanCode: $ratePlanCode !== null ? new RatePlanCode($ratePlanCode) : null,
));
return new JsonResponse(['id' => $reservationId->value], 201);
}
}The controller parses the request, generates the reservation id the way the Command-Query Separation lesson does, calls the handler, and returns a response. Nothing else.
There is no command bus between the controller and the handler. A bus earns its place when something must wrap every handler, such as a timer, an audit entry or a permission check, and nothing does here.
Step 5: The repositories
<?php
declare(strict_types=1);
namespace App\Reservations;
use App\Booking\RoomId;
use DateTimeImmutable;
interface Reservations
{
public function withId(ReservationId $id): Reservation;
public function existingFor(RoomId $roomId, DateRange $stayDates): ReservationCollection;
public function save(Reservation $reservation): void;
public function pendingCheckInsOn(DateTimeImmutable $date): ReservationCollection;
}<?php
declare(strict_types=1);
namespace App\Booking;
interface Rooms
{
public function withId(RoomId $id): Room;
}<?php
declare(strict_types=1);
namespace App\Booking;
use App\Billing\Currency;
final readonly class Room
{
public function __construct(
public RoomId $id,
public int $nightlyRateCents,
public Currency $currency,
public int $maxNights,
) {}
}<?php
declare(strict_types=1);
namespace App\Pricing;
interface RatePlans
{
public function withCode(RatePlanCode $code): ?RatePlan;
public function markUsed(RatePlanCode $code): void;
}The repositories are shaped in domain terms. Each has its own Eloquent implementation that maps rows to plain domain objects instead of returning models; the handlers don't import the implementations. EloquentRooms converts the legacy nightly_rate column (dollars) to nightlyRateCents and builds every room with Currency::usd(), because the legacy table has no currency column. This Room and the RatePlan in step 7 model the legacy tables, so they differ from the trimmed versions in the BDD lesson: rooms here hold a rate in cents, and rate plans count their uses. This Rooms interface also differs from the one in the Specification lesson, which has a single matching(RoomSpecification) method.
Step 6: A rich domain entity for reservations
<?php
declare(strict_types=1);
namespace App\Reservations;
use Ramsey\Uuid\Uuid;
final readonly class ReservationId
{
public function __construct(public string $value) {}
public static function next(): self
{
return new self(Uuid::uuid7()->toString());
}
}<?php
declare(strict_types=1);
namespace App\Reservations\Events;
use App\Billing\Money;
use App\Booking\GuestId;
use App\Booking\RoomId;
use App\Reservations\DateRange;
use App\Reservations\ReservationId;
final readonly class ReservationRequested
{
public function __construct(
public ReservationId $reservationId,
public GuestId $guestId,
public RoomId $roomId,
public DateRange $stayDates,
public Money $quotedPrice,
) {}
}The event carries the ids, the stay dates, and the quoted price, so listeners don't have to reload the reservation. It has no guest count because the original request has none.
<?php
declare(strict_types=1);
namespace App\Reservations;
use App\Billing\Money;
use App\Booking\GuestId;
use App\Booking\RoomId;
use App\Pricing\RatePlanCode;
use App\Reservations\Events\ReservationRequested;
use DateTimeImmutable;
final class Reservation
{
/** @var list<object> */
private array $recordedEvents = [];
public function __construct(
public readonly ReservationId $id,
public readonly RoomId $roomId,
public readonly GuestId $guestId,
public readonly DateRange $stayDates,
public readonly Money $totalPrice,
public readonly ?RatePlanCode $ratePlanCode,
public readonly DateTimeImmutable $createdAt,
) {}
public static function request(
ReservationId $id,
RoomId $roomId,
GuestId $guestId,
DateRange $stayDates,
Money $price,
?RatePlanCode $ratePlanCode,
DateTimeImmutable $now,
): self {
$reservation = new self(
id: $id,
roomId: $roomId,
guestId: $guestId,
stayDates: $stayDates,
totalPrice: $price,
ratePlanCode: $ratePlanCode,
createdAt: $now,
);
$reservation->recordedEvents[] = new ReservationRequested(
reservationId: $reservation->id,
guestId: $guestId,
roomId: $roomId,
stayDates: $stayDates,
quotedPrice: $price,
);
return $reservation;
}
/** @return list<object> */
public function releaseEvents(): array
{
$events = $this->recordedEvents;
$this->recordedEvents = [];
return $events;
}
}This is a trimmed Reservation, covering only the create path. It is a rich model with a named constructor (request) that records the event, which the handler releases. The entity owns its construction; the rules of "what does it mean to request a reservation" live here.
The controller now generates reservation ids as UUIDs and puts them in the command, and the handler passes them to request(). The database's auto-increment no longer assigns them, so the response id is a string. The reservations table needs a matching key column; that migration is outside this lesson.
Step 7: A price calculator
The original computed the price inline. A factory fits when building the value needs injected services, and a price that looks up a rate plan and decrements its uses_left would turn a calculation into a database write. Looking the rate plan up and consuming it belong to the handler, which leaves the pricing math with no collaborators, so a plain class is enough:
<?php
declare(strict_types=1);
namespace App\Pricing;
use App\Billing\Money;
use DateTimeImmutable;
use InvalidArgumentException;
final class RatePlan
{
public function __construct(
public readonly RatePlanCode $code,
public readonly string $type,
public readonly int $amount,
public readonly DateTimeImmutable $expiresAt,
private readonly int $usesLeft,
) {}
public function isValidAt(DateTimeImmutable $now): bool
{
return $this->expiresAt > $now && $this->usesLeft > 0;
}
public function applyTo(Money $base): Money
{
return match ($this->type) {
'percent' => $base->applyDiscountPercent($this->amount),
'fixed' => Money::fromCents(
max(0, $base->amountInCents - $this->amount),
$base->currency,
),
default => throw new InvalidArgumentException("Unknown rate plan type: {$this->type}"),
};
}
}amount is a percentage for percent plans and cents for fixed plans. The legacy column holds dollars for fixed plans, so EloquentRatePlans converts it to cents when it builds the RatePlan, and implements markUsed() as an atomic SQL decrement of uses_left. This is a trimmed RatePlan.
<?php
declare(strict_types=1);
namespace App\Pricing;
use App\Billing\Money;
use App\Booking\Room;
use App\Reservations\DateRange;
final readonly class StayPriceCalculator
{
public function quote(Room $room, DateRange $stayDates, ?RatePlan $ratePlan): Money
{
$base = Money::fromCents($room->nightlyRateCents, $room->currency)
->multiplyBy($stayDates->nights());
return $ratePlan === null ? $base : $ratePlan->applyTo($base);
}
}Step 8: The handler
<?php
declare(strict_types=1);
namespace App\Reservations;
use App\Booking\Rooms;
use App\Framework\Events\EventDispatcher;
use App\Pricing\RatePlan;
use App\Pricing\RatePlanCode;
use App\Pricing\RatePlans;
use App\Pricing\StayPriceCalculator;
use App\Reservations\Exceptions\ReservationTooLong;
use App\Reservations\Exceptions\SlotAlreadyBooked;
use App\Reservations\Exceptions\SlotBeingReserved;
use DateTimeImmutable;
use Psr\Clock\ClockInterface as Clock;
use Symfony\Component\Lock\LockFactory;
final readonly class RequestReservationCommandHandler
{
public function __construct(
private Rooms $rooms,
private Reservations $reservations,
private RatePlans $ratePlans,
private StayPriceCalculator $prices,
private LockFactory $locks,
private Clock $clock,
private EventDispatcher $events,
) {}
public function handle(RequestReservationCommand $command): void
{
$lock = $this->locks->createLock(
"room:{$command->roomId->value}:slot:{$command->stayDates->checkIn->toIso8601String()}"
);
if (!$lock->acquire()) {
throw new SlotBeingReserved($command->roomId, $command->stayDates);
}
try {
$now = $this->clock->now();
$room = $this->rooms->withId($command->roomId);
if ($room->maxNights < $command->stayDates->nights()) {
throw new ReservationTooLong($room->id, $command->stayDates);
}
if (! $this->reservations->existingFor($command->roomId, $command->stayDates)->isEmpty()) {
throw new SlotAlreadyBooked($command->roomId, $command->stayDates);
}
$ratePlan = $this->applicableRatePlan($command->ratePlanCode, $now);
$price = $this->prices->quote($room, $command->stayDates, $ratePlan);
$reservation = Reservation::request(
id: $command->reservationId,
roomId: $command->roomId,
guestId: $command->guestId,
stayDates: $command->stayDates,
price: $price,
ratePlanCode: $command->ratePlanCode,
now: $now,
);
$this->reservations->save($reservation);
if ($ratePlan !== null) {
$this->ratePlans->markUsed($ratePlan->code);
}
foreach ($reservation->releaseEvents() as $event) {
$this->events->dispatch($event);
}
} finally {
$lock->release();
}
}
private function applicableRatePlan(?RatePlanCode $code, DateTimeImmutable $now): ?RatePlan
{
if ($code === null) {
return null;
}
$ratePlan = $this->ratePlans->withCode($code);
return $ratePlan !== null && $ratePlan->isValidAt($now) ? $ratePlan : null;
}
}The handler orchestrates: it doesn't calculate the price, query directly or send emails, and each of those lives somewhere else. The existingFor repository method already returns only overlapping reservations, so the handler asks the returned ReservationCollection whether it is empty and does not loop over it. The event dispatcher is the course's own EventDispatcher interface, which lets the handler test in step 11 swap in a recording spy.
The lock key keeps the original's shape and is out of scope here, though the handler now writes the date with toIso8601String(). It is the room plus the check-in date, so two overlapping stays with different check-in dates take different locks and can still race. This refactor moves the code; it does not fix that.
symfony/lock is a separate Composer package (composer require symfony/lock), and the original controller already depended on it. The refactor keeps it so behavior stays identical. Laravel's Cache::lock() does the same job without the extra package, and switching to it would be a reasonable follow-up.
Step 9: Domain exceptions
The three failure modes (SlotBeingReserved, ReservationTooLong, SlotAlreadyBooked) are domain exceptions. They know nothing about HTTP:
<?php
declare(strict_types=1);
namespace App\Reservations\Exceptions;
use App\Booking\RoomId;
use App\Framework\Exceptions\DomainException;
use App\Reservations\DateRange;
final class SlotAlreadyBooked extends DomainException
{
public function __construct(
public readonly RoomId $roomId,
public readonly DateRange $stayDates,
) {
parent::__construct("Room {$roomId->value} is already booked for the requested slot");
}
}<?php
declare(strict_types=1);
namespace App\Reservations\Exceptions;
use App\Booking\RoomId;
use App\Framework\Exceptions\DomainException;
use App\Reservations\DateRange;
final class SlotBeingReserved extends DomainException
{
public function __construct(
public readonly RoomId $roomId,
public readonly DateRange $stayDates,
) {
parent::__construct("Room {$roomId->value} is being reserved by another request");
}
}<?php
declare(strict_types=1);
namespace App\Reservations\Exceptions;
use App\Booking\RoomId;
use App\Framework\Exceptions\DomainException;
use App\Reservations\DateRange;
final class ReservationTooLong extends DomainException
{
public function __construct(
public readonly RoomId $roomId,
public readonly DateRange $stayDates,
) {
parent::__construct("Room {$roomId->value} cannot be booked for {$stayDates->nights()} nights");
}
}The HTTP mapping lives in bootstrap/app.php, and it reproduces the three response bodies and status codes of the original controller:
<?php
declare(strict_types=1);
use App\Framework\Exceptions\DomainException;
use App\Reservations\Exceptions\ReservationTooLong;
use App\Reservations\Exceptions\SlotAlreadyBooked;
use App\Reservations\Exceptions\SlotBeingReserved;
use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
return Application::configure(basePath: dirname(__DIR__))
->withRouting(
web: __DIR__.'/../routes/web.php',
health: '/up',
)
->withMiddleware(function (Middleware $middleware): void {})
->withExceptions(function (Exceptions $exceptions): void {
$exceptions->dontReport(DomainException::class);
$exceptions->render(function (DomainException $e, Request $request) {
return match (true) {
$e instanceof SlotBeingReserved => new JsonResponse(['error' => 'slot is being reserved'], 409),
$e instanceof SlotAlreadyBooked => new JsonResponse(['error' => 'slot already booked'], 409),
$e instanceof ReservationTooLong => new JsonResponse(['error' => 'stay too long'], 422),
default => null,
};
});
})
->create();The controller never catches these, and dontReport keeps them out of the log because the original returned these responses without logging anything. A closure that returns null falls back to Laravel's default rendering, so other domain exceptions keep working while you add them to the match.
Step 10: Side effects via events
The mailer call and the logger call from the original controller are now reactions to ReservationRequested:
<?php
declare(strict_types=1);
namespace App\Reservations\Listeners;
use App\Reservations\Events\ReservationRequested;
use App\Reservations\Mail\ReservationConfirmedEmail;
use Illuminate\Contracts\Mail\Mailer;
final readonly class SendReservationConfirmation
{
public function __construct(private Mailer $mailer) {}
public function handle(ReservationRequested $event): void
{
$this->mailer->send(new ReservationConfirmedEmail($event->reservationId));
}
}<?php
declare(strict_types=1);
namespace App\Reservations\Listeners;
use App\Reservations\Events\ReservationRequested;
use Psr\Log\LoggerInterface;
final readonly class LogReservationRequested
{
public function __construct(private LoggerInterface $logger) {}
public function handle(ReservationRequested $event): void
{
$this->logger->info('reservation.created', [
'id' => $event->reservationId->value,
'user' => $event->guestId->value,
]);
}
}Each listener is tiny. The handler doesn't care that these exist; they're consumers of the event. ReservationConfirmedEmail is the existing mailable renamed to match the course. It now receives a ReservationId instead of the int id, and it looks up the recipient from the reservation id.
These listeners live outside app/Listeners, so Laravel will not find them on its own. The service provider registers them, along with the bindings the handler needs:
<?php
declare(strict_types=1);
namespace App\Providers;
use App\Booking\Infrastructure\EloquentRooms;
use App\Booking\Rooms;
use App\Framework\Events\EventDispatcher;
use App\Framework\Events\LaravelEventDispatcher;
use App\Pricing\Infrastructure\EloquentRatePlans;
use App\Pricing\RatePlans;
use App\Reservations\Events\ReservationRequested;
use App\Reservations\Infrastructure\EloquentReservations;
use App\Reservations\Listeners\LogReservationRequested;
use App\Reservations\Listeners\SendReservationConfirmation;
use App\Reservations\Reservations;
use App\Support\SystemClock;
use Illuminate\Support\Facades\Event;
use Illuminate\Support\ServiceProvider;
use Psr\Clock\ClockInterface;
use Symfony\Component\Lock\LockFactory;
use Symfony\Component\Lock\Store\FlockStore;
final class AppServiceProvider extends ServiceProvider
{
public function register(): void
{
$this->app->singleton(
LockFactory::class,
fn (): LockFactory => new LockFactory(new FlockStore()),
);
$this->app->bind(ClockInterface::class, SystemClock::class);
$this->app->bind(EventDispatcher::class, LaravelEventDispatcher::class);
$this->app->bind(Reservations::class, EloquentReservations::class);
$this->app->bind(Rooms::class, EloquentRooms::class);
$this->app->bind(RatePlans::class, EloquentRatePlans::class);
}
public function boot(): void
{
Event::listen(ReservationRequested::class, SendReservationConfirmation::class);
Event::listen(ReservationRequested::class, LogReservationRequested::class);
}
}FlockStore keeps locks as files, so it only works when every process runs on one machine (see the Symfony Lock docs). With more than one server, the lock needs a store all servers share.
Step 11: The tests that kept us honest
The characterization test from step 1 never changed, and each commit of the refactor kept it passing exactly as written. It proves the happy path, a stay with no rate plan, kept its response and its row. It says nothing about the paths it doesn't exercise, and a few things changed on purpose: the rate_plan_code regex rule in step 2, the UUID reservation id from step 6, the rate plan's uses_left now dropping after the reservation is saved instead of before, and the fixed-amount rate plan unit moving from dollars to cents (converted in EloquentRatePlans). Two more come from the new types: the lock key now holds the date in ISO-8601 form, so old and new code take different locks for the same slot while both run during a deploy, and a percent rate plan above 100 now throws in Money::applyDiscountPercent(), where the original produced a negative price. The three error responses keep their original bodies and status codes through the mapping in step 9. Each of those changes went in as its own commit with the feature hat on (the two hats from the refactoring lesson), separate from the refactoring steps.
Step 6 introduced Reservation::request(). It gets its own unit test, no framework, no database:
<?php
declare(strict_types=1);
namespace Tests\Reservations;
use App\Billing\Currency;
use App\Billing\Money;
use App\Booking\GuestId;
use App\Booking\RoomId;
use App\Reservations\DateRange;
use App\Reservations\Events\ReservationRequested;
use App\Reservations\Reservation;
use App\Reservations\ReservationId;
use Carbon\CarbonImmutable;
use DateTimeImmutable;
use PHPUnit\Framework\TestCase;
final class ReservationRequestTest extends TestCase
{
public function test_requesting_a_reservation_keeps_the_inputs_and_records_the_event(): void
{
$roomId = new RoomId(14);
$guestId = new GuestId(501);
$stayDates = new DateRange(
CarbonImmutable::parse('2026-06-01'),
CarbonImmutable::parse('2026-06-03'),
);
$price = Money::fromCents(20000, Currency::usd());
$now = new DateTimeImmutable('2026-05-20');
$reservationId = ReservationId::next();
$reservation = Reservation::request(
id: $reservationId,
roomId: $roomId,
guestId: $guestId,
stayDates: $stayDates,
price: $price,
ratePlanCode: null,
now: $now,
);
$this->assertSame($reservationId, $reservation->id);
$this->assertEquals($roomId, $reservation->roomId);
$this->assertEquals($guestId, $reservation->guestId);
$this->assertTrue($reservation->totalPrice->equals($price));
$this->assertEquals($now, $reservation->createdAt);
$events = $reservation->releaseEvents();
$this->assertCount(1, $events);
$this->assertInstanceOf(ReservationRequested::class, $events[0]);
$this->assertSame([], $reservation->releaseEvents());
}
}Step 5 introduced the Reservations, Rooms, and RatePlans interfaces; step 6 introduced ReservationRequested. Once both existed, the handler earned a test built from in-memory fakes and a recording dispatcher. InMemoryReservations is the one from the test doubles lesson and RecordingDispatcher is the one from the dependency injection lesson. The test and the handler use only save, withId and existingFor on the former. Its pendingCheckInsOn calls status(), which this trimmed Reservation doesn't have, and the test never reaches it. The two fakes below are new:
<?php
declare(strict_types=1);
namespace App\Testing;
use App\Booking\Room;
use App\Booking\RoomId;
use App\Booking\Rooms;
use OutOfBoundsException;
final class InMemoryRooms implements Rooms
{
/** @var array<int, Room> */
private array $rooms = [];
public function add(Room $room): void
{
$this->rooms[$room->id->value] = $room;
}
public function withId(RoomId $id): Room
{
return $this->rooms[$id->value] ?? throw new OutOfBoundsException("Room {$id->value} not found");
}
}<?php
declare(strict_types=1);
namespace App\Testing;
use App\Pricing\RatePlan;
use App\Pricing\RatePlanCode;
use App\Pricing\RatePlans;
final class InMemoryRatePlans implements RatePlans
{
/** @var array<string, RatePlan> */
private array $ratePlans = [];
/** @var list<string> */
public array $used = [];
public function withCode(RatePlanCode $code): ?RatePlan
{
return $this->ratePlans[$code->value] ?? null;
}
public function add(RatePlan $ratePlan): void
{
$this->ratePlans[$ratePlan->code->value] = $ratePlan;
}
public function markUsed(RatePlanCode $code): void
{
$this->used[] = $code->value;
}
}<?php
declare(strict_types=1);
namespace Tests\Reservations;
use App\Billing\Currency;
use App\Booking\GuestId;
use App\Booking\Room;
use App\Booking\RoomId;
use App\Pricing\StayPriceCalculator;
use App\Reservations\DateRange;
use App\Reservations\Events\ReservationRequested;
use App\Reservations\RequestReservationCommand;
use App\Reservations\RequestReservationCommandHandler;
use App\Reservations\ReservationId;
use App\Testing\FrozenClock;
use App\Testing\InMemoryRatePlans;
use App\Testing\InMemoryReservations;
use App\Testing\InMemoryRooms;
use App\Testing\RecordingDispatcher;
use Carbon\CarbonImmutable;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Lock\LockFactory;
use Symfony\Component\Lock\Store\InMemoryStore;
final class RequestReservationCommandHandlerTest extends TestCase
{
public function test_it_requests_a_reservation_and_dispatches_the_event(): void
{
$roomId = new RoomId(14);
$rooms = new InMemoryRooms();
$rooms->add(new Room(
id: $roomId,
nightlyRateCents: 10000,
currency: Currency::usd(),
maxNights: 14,
));
$reservations = new InMemoryReservations();
$dispatcher = new RecordingDispatcher();
$handler = new RequestReservationCommandHandler(
rooms: $rooms,
reservations: $reservations,
ratePlans: new InMemoryRatePlans(),
prices: new StayPriceCalculator(),
locks: new LockFactory(new InMemoryStore()),
clock: new FrozenClock('2026-05-20'),
events: $dispatcher,
);
$reservationId = ReservationId::next();
$handler->handle(new RequestReservationCommand(
reservationId: $reservationId,
guestId: new GuestId(501),
roomId: $roomId,
stayDates: new DateRange(
CarbonImmutable::parse('2026-06-01'),
CarbonImmutable::parse('2026-06-03'),
),
ratePlanCode: null,
));
$saved = $reservations->withId($reservationId);
$this->assertEquals($roomId, $saved->roomId);
$this->assertEquals(new GuestId(501), $saved->guestId);
$this->assertSame(20000, $saved->totalPrice->amountInCents);
$this->assertCount(1, $dispatcher->dispatched);
$this->assertInstanceOf(ReservationRequested::class, $dispatcher->dispatched[0]);
}
}This test runs without a database, a lock backend, or a mail server.
The characterization test guards the observable behavior from outside, the entity test guards one rule in isolation, and the handler test guards the orchestration in between.
What we didn't use, and why
The course covers a lot of patterns. Several didn't fit this example:
Specification Pattern. The "is this slot available?" rule is small enough that a method on the repository is fine. The pattern doesn't earn its place here; it would for a larger combinatorial rule like "rooms eligible for the long-stay discount across multiple properties".
Decorator. No cross-cutting concern was added beyond what the framework's logger already provides. If the team later wants caching, metrics, or retries on the repositories, that's where decorators slot in.
Strategy. There's only one pricing approach at the moment. If a second appears (weekend pricing, partner-tier pricing, channel-specific pricing), promoting the inline calculation to a strategy makes sense. Cancellation policies are a strategy too, but they didn't show up here because the example only covers the create path.
Result objects. The failure modes here are exceptional enough that exceptions are the right tool. If the handler grew to "request reservation or fall back to waitlist", a result object might fit better.
Null Object. Nullability is small here (
?RatePlanCode). Wrapping it in aNoRatePlanwould be over-engineering.NullCancellationPolicydoes earn its place once the cancellation flow is in scope; not here.Singleton. Not needed. Container singleton bindings handle the "one instance" cases.
Unit of Work. The original had no transaction around the insert and the rate plan decrement, and the refactor keeps its behavior. Wrapping the save and the
markUsed()call in the handler's transaction, as the Unit of Work lesson shows, is the first follow-up.Pipeline. The price is one rate plan applied to one base amount. A pipeline fits once several adjustments, such as a weekly discount followed by a promotion, run in a fixed order.
State. The example only creates a reservation. State earns its place when confirming, checking in and cancelling each allow different transitions.
Builder. Every argument to
Reservation::request()is required, so a builder would only rename the constructor call. It fits an object with many optional parts.Queries, CQRS and the query bus. The feature is a single write with no read side to separate. A read model that needs a different shape from the write model is the trigger.
Command and event buses. Step 4 covers the command bus. The course's
EventDispatcheris the event bus from the Event Bus lesson, and it already carries the one event to its two listeners. Queueing those listeners is a follow-up for when the mail should go out from a worker instead of the request.Mutation testing. Pricing is the kind of critical logic it suits, but the mutation testing lesson puts it after the suite already has decent coverage, and this refactor has three tests.
The final shape
The refactored version is roughly:
1 controller.
1 form request.
1 command + 1 handler.
5 value objects (
GuestId,RoomId,ReservationId,RatePlanCode,DateRange), plus the course'sMoney.1 entity (reservation), 1 rate plan, 1 room.
3 repository interfaces (+ Eloquent implementations).
1 price calculator.
1 event + 2 listeners.
3 domain exceptions, mapped in
bootstrap/app.php.1 characterization test, 1 entity test, 1 handler test.
That's more files and more lines, and a new developer has more pieces to learn. The gain is that new work has an obvious place. "Send a Slack notification when a room is reserved" is a new listener on ReservationRequested. "Different pricing for VIP guests" goes in StayPriceCalculator, which becomes a strategy or grows a branch. The rules sit in named methods on named types, not in a controller.
Whether the extra files pay off depends on the context. A weekend tool can stay as the original controller. A product that will be maintained for years is where the smaller blast radius per change (the flatter cost-of-change curve) is worth it.
The one thing to remember
Each pattern in the course answers a problem you can point at in the code. Reach for a pattern when you can name the problem it solves.
Related Links
- Refactoring catalogMartin Fowler's catalog of named refactorings, several of which this lesson's steps are instances of.
- CodeSmellFowler's definition of a code smell, the concept behind this lesson's smell inventory.
- Commandthe pattern behind turning the original controller's inline logic into the command and handler used from step 4 onward.
- DomainEventFowler's description of using an event to capture something that happened in the domain, the shape ReservationRequested follows in step 10.
- Symfony Lockthe component behind the LockFactory and InMemoryStore used in the handler and its test.