Skip to content

Lesson 15 of 15 · Putting It Together

Capstone: Legacy Laravel App to Modular Monolith

Advanced•
lesson•
November 16, 2026•
~10 min read

What this lesson is for

You've read fourteen lessons on architectural styles, module boundaries, and migration strategy, on top of Building Maintainable PHP Applications: Foundations and Building Maintainable PHP Applications: Patterns and Principles. The danger of finishing a course like this is that the patterns sit in your head as a list of nouns, with no story for how they fit together when you walk into a real codebase on Monday morning.

This lesson follows a single scenario: a legacy SaaS product, two years in, with a familiar set of problems. A team applies what it has learned, in the order it would actually happen on the ground. Not every pattern shows up.

The example is Hearth, the hotel reservation product this course has used throughout. By the end, the product has a modular monolith with vertical slices, ports and adapters, and clean boundaries between the parts that used to be one tangled app/ folder. What the modules do with the domain rules once they're isolated, aggregates, ubiquitous language, the deeper modeling work, is the subject of the capstone in Building Maintainable PHP Applications: Domain-Driven Design. This lesson stops at the wall; that course picks up on the other side of it.

The starting state

A two-year-old Laravel application. The team has shipped features steadily; the codebase has grown along the path of least resistance. A quick inventory:

  • 60 routes, going to fat controllers in app/Http/Controllers/.

  • 40 service classes in app/Services/, each with 5-30 methods.

  • 25 Eloquent models in app/Models/, several over 500 lines.

  • One database. Tables named after what they store, columns named after what was easy.

  • A test suite that takes 8 minutes and is "mostly green most of the time".

  • One team of five engineers. The backlog is full. Management wants more features, not refactors.

The product itself: a hotel reservation system. Guests reserve rooms for date ranges, with rate plans, cancellation policies, channel manager integrations (Booking.com, Expedia), and payment processing through Stripe.

The team has read this course series. It wants to apply what it read. Management is sympathetic but not granting a rewrite budget.

Step 1: Honest mapping

Before any code changes, the team maps what's there. The output is three documents.

A smell inventory: what's painful right now. Slow tests, fat controllers, the User model with 800 lines, the BookingService with 30 methods, the cache that's regularly stale, the queue worker that randomly fails. Each smell is named, with the Foundations or Patterns and Principles lesson it maps to.

A module sketch: reading the existing code with module boundaries in mind, the team identifies probable module boundaries: Booking, Pricing, Housekeeping, Guest Profile, Payments, Notifications. Some are clearly distinct; some overlap. The sketch is a hypothesis about where the lines should go, drawn from code smells and team ownership. For now, they're folders with a purpose.

A pain priority: where does the team hurt most? Where are most bugs filed? Where does the test suite slow down hardest? Booking is the answer for all three. Booking goes first.

Step 2: The first slice

The next booking feature on the roadmap is "staff can confirm a pending reservation once payment clears." The migration lesson called this the first slice: pick one real feature, build it in the new shape, and ship it next to the old code without touching anything around it.

TEXT
Hearth/Booking/ ├── ConfirmReservation/ # the first slice │ ├── ConfirmReservationController.php │ ├── ConfirmReservationRequest.php │ ├── ConfirmReservationCommand.php │ ├── ConfirmReservationCommandHandler.php │ ├── ConfirmReservationResource.php │ └── ReservationConfirmed.php # event ├── Reservation/ │ ├── Reservation.php │ ├── ReservationId.php │ ├── ReservationStatus.php │ └── Reservations.php # port ├── Infrastructure/ │ ├── EloquentReservations.php # adapter │ └── ReservationRecord.php # Eloquent model ├── Tests/ │ └── ConfirmReservationCommandHandlerTest.php ├── DateRange.php ├── Dispatcher.php # port ├── PaymentAuthorization.php └── RoomId.php

Booking owns its own RoomId, DateRange, PaymentAuthorization and Dispatcher. Every other module will own its types too, and Booking imports none of them.

The handler depends on a port, not on Eloquent:

PHP
<?php declare(strict_types=1); namespace Hearth\Booking\Reservation; use Hearth\Booking\DateRange; use Hearth\Booking\RoomId; interface Reservations { public function withId(ReservationId $id): Reservation; public function save(Reservation $reservation): void; /** @return list<Reservation> */ public function overlapping(RoomId $roomId, DateRange $stayDates): array; }
PHP
<?php declare(strict_types=1); namespace Hearth\Booking\ConfirmReservation; use Carbon\CarbonImmutable; use Hearth\Booking\PaymentAuthorization; use Hearth\Booking\Reservation\ReservationId; final readonly class ConfirmReservationCommand { public function __construct( public ReservationId $reservationId, public PaymentAuthorization $paymentAuthorization, public CarbonImmutable $confirmedAt, ) {} }
PHP
<?php declare(strict_types=1); namespace Hearth\Booking\ConfirmReservation; use Hearth\Booking\Dispatcher; use Hearth\Booking\Reservation\Reservations; final readonly class ConfirmReservationCommandHandler { public function __construct( private Reservations $reservations, private Dispatcher $dispatcher, ) {} public function handle(ConfirmReservationCommand $command): void { $reservation = $this->reservations->withId($command->reservationId); $reservation->confirm($command->paymentAuthorization, $command->confirmedAt); $this->reservations->save($reservation); foreach ($reservation->releaseEvents() as $event) { $this->dispatcher->dispatch($event); } } }

confirm() refuses a reservation that isn't pending and records ReservationConfirmed; releaseEvents() hands back what it recorded. This lesson only shows the two calls the handler makes.

The adapter that satisfies the port lives in Infrastructure/, next to ReservationRecord, the Eloquent model it reads and writes. Those two are the only Booking files that touch Eloquent:

PHP
<?php declare(strict_types=1); namespace Hearth\Booking\Infrastructure; use Hearth\Booking\DateRange; use Hearth\Booking\Reservation\Reservation; use Hearth\Booking\Reservation\ReservationId; use Hearth\Booking\Reservation\Reservations; use Hearth\Booking\Reservation\ReservationStatus; use Hearth\Booking\RoomId; final readonly class EloquentReservations implements Reservations { public function withId(ReservationId $id): Reservation { return ReservationRecord::query()->findOrFail($id->toString())->toDomain(); } public function save(Reservation $reservation): void { ReservationRecord::query()->updateOrCreate( ['id' => $reservation->id->toString()], ReservationRecord::fromDomain($reservation), ); } /** @return list<Reservation> */ public function overlapping(RoomId $roomId, DateRange $stayDates): array { return ReservationRecord::query() ->where('room_id', $roomId->toString()) ->where('status', '!=', ReservationStatus::CANCELLED->value) ->where('check_in', '<', $stayDates->checkOut) ->where('check_out', '>', $stayDates->checkIn) ->get() ->map(fn (ReservationRecord $row): Reservation => $row->toDomain()) ->all(); } }

ReservationRecord::toDomain() and fromDomain() are left out here, as in the Request Lifecycle lesson. This adapter's job is to get a row in and get a row out.

ConfirmReservationCommandHandler never imports Illuminate\*, and it doesn't care what toDomain() does internally. Swap EloquentReservations for an in-memory fake in a test and the handler doesn't notice. The team has a working seed for the new architecture, a folder it can point at in every PR review from here on.

Step 3: Module folders and the enforcement wall

Encouraged by the first slice, the team makes the structure more visible. Top-level folders for each module candidate from the Step 1 sketch:

TEXT
Hearth/ ├── Booking/ # new ├── GuestProfile/ # placeholder, wraps the legacy User ├── Pricing/ # placeholder ├── Payments/ # placeholder ├── Housekeeping/ # placeholder └── Notifications/ # placeholder

Discipline alone doesn't hold a boundary under deadline pressure, so the team adds a PHPArkitect rule. PHPArkitect (phparkitect/arkitect on GitHub) lets you write architectural constraints as PHP and run them in CI. It is the same tool the framework code lesson configured and the modular monolith lesson described:

PHP
<?php declare(strict_types=1); use Arkitect\ClassSet; use Arkitect\CLI\Config; use Arkitect\Expression\ForClasses\NotDependsOnTheseNamespaces; use Arkitect\Expression\ForClasses\ResideInOneOfTheseNamespaces; use Arkitect\Rules\Rule; return static function (Config $config): void { $classSet = ClassSet::fromDir(__DIR__.'/Hearth'); $modules = ['Booking', 'Housekeeping', 'Payments', 'Pricing', 'GuestProfile', 'Notifications']; $allowedFromBooking = [ 'Notifications' => ['Hearth\Booking\ConfirmReservation\ReservationConfirmed'], ]; $rules = []; foreach ($modules as $module) { $otherModules = array_map( static fn (string $other): string => "Hearth\\{$other}", array_values(array_diff($modules, [$module])), ); $rules[] = Rule::allClasses() ->that(new ResideInOneOfTheseNamespaces("Hearth\\{$module}")) ->should(new NotDependsOnTheseNamespaces($otherModules, $allowedFromBooking[$module] ?? [])) ->because("{$module} imports nothing from another module except a listener's event"); } $config->add($classSet, ...$rules); };

Saved as phparkitect.php at the project root and run with vendor/bin/phparkitect check in CI, this fails the build the moment a PR imports across the wall. No class in any module can import from another, with one listed exception: Notifications may import ReservationConfirmed, the event its listener handles in Step 5.

The legacy code stays where it is, in app/. The new code lives in Hearth/, which Composer maps to the Hearth\ namespace. Nothing is forced to move. New work lands in the new folders. PRs that try to add new code to app/Services/ get flagged in review, and now the tooling backs the reviewer up instead of leaving it to memory. The wall is up, even though it's mostly empty on the new side.

Step 4: Strangling Booking

The Booking module gets the strangler-fig treatment from the Strangler Fig lesson. One reservation operation at a time:

  • Request reservation: new slice, behind a feature flag, gradual rollout.

  • Confirm reservation: the slice built in Step 2, already live.

  • Cancel reservation: same shape as the Vertical Slice Architecture lesson's worked example.

  • Check in guest and check out guest: same.

  • View reservation details: new query slice.

  • List reservations for a guest: new query slice.

Each migration follows the phase sequence from the migration lesson: characterization tests first, then a Form Request, then a command and handler, then a repository port, then value objects in place of primitives, then rules moved into the entity. The legacy BookingController shrinks as methods are deleted once their replacements stabilize at 100% of traffic.

All reservation traffic flows through the new slices. The legacy BookingService is still there, still used by some admin reports. Nobody touches it. It's stable code that doesn't justify the cost of migrating it.

Step 5: The cross-module event seam

As Booking stabilizes, the Notifications module gets built alongside it. Its only job is to react to events from other modules and send notifications.

TEXT
Hearth/Notifications/ ├── SendConfirmationEmail/ │ ├── GuestEmails.php # its own address lookup │ ├── ReservationConfirmationMail.php │ └── SendConfirmationEmailListener.php └── NotificationsServiceProvider.php

Booking doesn't know Notifications exists. It dispatches the events Reservation releases, nothing more; whatever listens, listens. NotificationsServiceProvider registers each listener with Event::listen(ReservationConfirmed::class, SendConfirmationEmailListener::class), and every listener is named <Reaction>Listener. A cancellation listener would have the same shape. GuestEmails is the interface Notifications defines for itself to look up a guest's address, as in the modular monolith lesson. Each listener imports the event class and nothing else from Booking, and the events carry ids and timestamps, so Notifications never needs a Booking value object. The PHPArkitect rule from Step 3 enforces both directions, with the event import as the one listed exception.

The event is the mechanism that keeps Notifications from importing Booking. Adding an SMS notification later means adding a new listener file; nothing in Booking changes.

Step 6: What didn't get migrated (and that's fine)

The migration isn't "done". A few legacy areas remain:

  • Admin tools. Internal interfaces for support staff. CRUD-shaped, low traffic, low change rate. They never moved out of app/. They didn't need to.

  • A reporting export job. Runs once a quarter. Reads from the database directly, builds a CSV, emails it. Untouched. Works fine.

  • A legacy channel manager integration. Specific to one channel that's about to be sunset. The team chose not to migrate code that won't live much longer.

The value lands where code is heavily used and frequently changed. The rest can stay in app/.

What the team has now

A modular monolith with five module candidates (Booking, Pricing, Housekeeping, Guest Profile, Payments) and a Notifications module, enforced by a PHPArkitect rule that fails CI on a cross-import. Vertical slices for every migrated use case. Hexagonal-flavored discipline inside each slice: commands, handlers, ports, adapters. Events as the mechanism that keeps modules decoupled. A test suite that runs the domain logic in seconds where it's been migrated. The legacy code in app/ shrinks slowly as it is touched and migrated.

The team didn't do a rewrite or pause feature work, and each PR was small enough to review. It's not a final destination; the codebase keeps evolving. But it's a meaningfully better place than where it started, and the walls are now in the right places for the next course to build behind them.

What the next course picks up

Two more areas grow out of this migration: a Guest Profile module built around the legacy User model and a Payments module wrapping the Stripe integration. Both raise real questions, what the guest entity should own, how to protect the domain from Stripe's shapes, how far the aggregate boundary extends, that are about modeling the domain correctly. That work belongs to Domain-Driven Design and its own capstone, which resumes this exact scenario from where this lesson leaves it.

You now have the vocabulary from Foundations and Patterns and Principles, plus the structural patterns from this course, to take an existing PHP product and give it real boundaries without a rewrite.

The one thing to remember

A module boundary and a domain model are two different jobs. This course teaches you to draw the wall and enforce it; the next one teaches you what belongs on each side of it.

Course Content

Sign in to track your progress