Skip to content

Lesson 13 of 15 · Applying It to Real Projects

Migrating a Legacy PHP App Step by Step

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

Monday morning

You finish Building Maintainable PHP Applications: Foundations. You finish Building Maintainable PHP Applications: Patterns and Principles. You're most of the way through this course. You close the laptop, sleep, and go to your job on Monday.

You open the codebase you've been working on for two years. There are 60 controllers, several over 400 lines. There are 40 service classes, all named SomethingService, most with twenty methods. The Reservation model is 800 lines and imports half the application. There are no module boundaries. The tests are slow and flaky. You have a sprint that starts tomorrow with three new features in it.

You're not getting a rewrite budget, and you're not stopping feature work. The patterns from this course look great in greenfield code, but the codebase you actually own looks nothing like that. So how do you apply any of it?

This lesson is the playbook.

The truth about migrations

Big-bang refactors fail. They run long, ship in a worse state than they started, and burn out the team that proposed them. I have watched this happen more than once.

The migration that actually works is incremental, opportunistic, and measured in months or years - not weeks. It is boring. It produces no demo-friendly milestones. The team has to be patient with itself, and the team's manager has to be patient with the team.

Three principles before you start

No new mess. New features land in the new shape. Commands, handlers, value objects, repository interfaces, the patterns from this course. Old code stays as-is until you have a reason to touch it. The line in the sand is "from today, no new code that looks like the old stuff".

Touched code gets cleaned up. When you have to modify old code anyway - for a feature, a bug, a config change - apply the Boy Scout Rule: leave it slightly better than you found it. Apply the patterns where it's cheap. Do not try to fix the whole file. Just the bit you touched.

Strategic refactors are projects. Some cleanup is too big for the Boy Scout Rule. Migrating a 1,200-line BookingService is not a casual side-quest in a feature PR. That work goes on the roadmap, gets scoped, gets buy-in, and ships like a feature. Pretending it can be done on the side is how big-bang refactors start.

The first slice

The recommended first move is small. Pick one new feature on the roadmap. Build it as a vertical slice. Use a command and handler. Use a repository interface. Validate with a Form Request. Test it the way the new patterns want to be tested.

Do not try to refactor anything around it. Do not touch the controllers next door. Do not "just clean up" the model it uses. Build the new slice cleanly, alongside the old code, and ship it.

This is the seed. After it lands, you have a concrete example in your codebase of "this is what new features look like". You can point at it in PR review. You can point at it in onboarding. The pattern stops being abstract and starts being a file path.

Stranglers grow around the seed

As more features arrive, more slices get added. Each new slice replaces some piece of an old service or controller. The old code does not vanish; it just stops growing. The new slices grow next to it, taking work off it one feature at a time.

Later, the old BookingService still exists, but its method count is going down. New behavior lives in slices. Old behavior peels off when it gets touched. The old service is being strangled, slowly, in place.

The next lesson is the deep version of this idea: the Strangler Fig pattern, named by Martin Fowler, which is the architectural shape this work takes.

A practical sequence for one fat controller

Take a single 400-line BookingController from the legacy codebase. Here is how to migrate it incrementally, one PR at a time. Each PR is small enough to review.

Phase 0: Cover with characterization tests. Before you change a line, write tests that pin down the current behavior, including the bugs. Michael Feathers calls these characterization tests in Working Effectively with Legacy Code. Do not refactor without tests. The tests do not need to be pretty. They need to fail loudly when behavior changes.

Phase 1: Move validation into a Form Request. Tiny change. The controller stops doing inline validation. The Form Request holds the rules. Easy to review, easy to roll back, little risk to behavior; the phase 0 tests catch a changed error response.

Phase 2: Pick one method (e.g. confirmReservation). Extract a command and handler. The controller method becomes three lines: build the command from the request, dispatch it, return the response. The handler holds the logic that used to live in the controller. Tests stay green.

Phase 3: Introduce a repository interface for that handler. The handler stops calling Reservation::find() directly. It depends on a Reservations interface, with an Eloquent adapter behind it that still hands back the old Eloquent model for now. The handler can now be tested without a database.

Phase 4: Lift primitives into value objects. The handler stops passing string $reservationId and string $authorizationCode around. It uses ReservationId and PaymentAuthorization. The validation moves into the value objects.

Phase 5: Push rules from the handler into the entity. The handler stops doing if ($reservation->status === 'pending') { ... }. The rule moves onto a new plain-PHP Reservation entity in Hearth/Booking/Reservation/, as a method. The adapter now maps the Eloquent row to that entity and back, the way EloquentReservations does in the Hexagonal Architecture lesson, and the model in app/Models/ loses nothing yet. The handler orchestrates; the entity decides.

Where the files sit after phase 5, with the phase that added each one:

TEXT
app/ # legacy, App\ ├── Http/ │ ├── Controllers/ │ │ └── BookingController.php # phases 1, 2 │ └── Requests/ │ └── ConfirmReservationRequest.php # phase 1 └── Models/ └── Reservation.php # god model Hearth/Booking/ # new, Hearth\ ├── ConfirmReservation/ │ ├── ConfirmReservationCommand.php # phase 2 │ └── ConfirmReservationCommandHandler.php # phase 2 ├── Reservation/ │ ├── Reservation.php # phase 5 │ ├── Reservations.php # phase 3 │ └── ReservationId.php # phase 4 ├── Infrastructure/ │ └── EloquentReservations.php # phase 3 ├── Tests/ │ └── ConfirmReservationCommandHandlerTest.php # phase 3 └── PaymentAuthorization.php # phase 4 tests/Feature/ └── BookingControllerTest.php # phase 0

Each phase is a single PR. Tests stay green throughout. Other developers can apply the same playbook to other controllers in parallel. The team gets faster at it after the first three or four.

A practical sequence for the fat Reservation model

Same idea, applied to a model rather than a controller.

Start by listing the reasons the model changes. Group the methods by responsibility. The Reservation Eloquent model is probably doing six unrelated jobs: availability checking, pricing, payment status tracking, guest notifications, housekeeping triggers, and audit. That list is your migration map.

For each new feature involving the reservation, push that responsibility into a slice or a domain method, not back into the god model. If the feature is "send a pre-arrival reminder", the slice owns the reminder logic; the Reservation model does not get a sendPreArrivalReminder() method bolted on.

Over time, the fat model thins out. Behavior migrates outward into slices and domain entities. The Eloquent class becomes a persistence shell with a few accessors and relationships. You just stopped feeding it.

What to migrate first

Prioritize ruthlessly. Three signals:

Pain. Where does the team actually hurt? Slow tests, fragile features, frequent regressions, the file everyone groans at in standup. Migrate that. The pain pays back the work directly.

Frequency of change. Code that changes weekly is worth cleaning up. Code that has not been touched in a long time is fine where it is. Git lists the hot spots, most-changed files first:

BASH
git log --format= --name-only | sort | uniq -c | sort -rn | head -20

Those files are the migration targets.

Strategic importance. Core business areas, where correctness matters and the business cares about velocity, get the budget. Edge tools and one-off scripts do not.

Do not migrate code "because it is ugly" if it works and never changes. Your time is the scarce resource.

What not to migrate

The stable, working, ugly code. The internal admin tool that nobody complains about. The export script that has run fine for years. The old onboarding flow that is being sunsetted anyway.

Anything where the migration cost exceeds the maintenance cost stays exactly as it is. Be selective. The migration is a budget; spend it where it earns out.

The hardest part is people

A migration like this is a culture shift. The technical work is straightforward; getting twelve developers, two staff engineers, and one skeptical manager all rowing in the same direction is the actual job.

You need a few people who understand the patterns and can champion them in PR review. You need PR reviews that catch and educate (gently) when new code lands in the old shape. "Hey, this could be a slice; here is the example one we built." You need a documented "this is how we build new features" page that the team agrees on. And you need patience, because it will feel like nothing is changing.

If the senior people on the team are not on board, the migration does not happen. Get that alignment first.

Anti-patterns during migration

A few patterns that often burn the team:

  • "Let's freeze features and refactor." This always blows up. The product team revolts, the refactor goes long, and the codebase ships in a worse state than it started.

  • "Let's rewrite from scratch." Joel Spolsky wrote "Things You Should Never Do, Part I" in 2000 and it is still right. Rewrites end with the same problems in a new codebase, plus the lost feature work. The bugs you knew about are gone; new ones replaced them.

  • "Let's apply the patterns to every file we open." Scope creep. A two-line bug fix turns into a 400-line PR nobody wants to review. Touch only what the change requires.

  • "New features in the new shape, but never clean up old code." Half measures. The codebase becomes two codebases, each with its own conventions, and onboarding gets harder.

  • "Let's parallel-build a v2 alongside v1." Massive coordination cost. Usually the v2 ships incomplete, the team is back to maintaining v1, and now there are two of everything.

Pragmatic stopping points

You do not have to march all the way to "perfect Hexagonal + DDD". There are healthy waystations, each of which is a real win on its own:

  • Vertical Slice Architecture everywhere. All new features in slices. Old code stays. Tests are fast. PRs are small. This alone is a big improvement over the legacy shape.

  • Slices plus repositories. New code uses repository interfaces. The Eloquent layer is contained. Tests run without the database.

  • Domain entities for the core domain only. The Booking module gets rich entities that enforce their own rules. The admin tools stay CRUD. You spend the modeling budget where the business actually cares.

  • Bounded contexts as folders. Major modules become enforced folders; cross-imports get caught by tooling. Even if the inside of each module is not fully DDD, the boundaries help.

Tooling that helps

A few things make the work less painful:

  • PHPStan or Psalm at a high level catches type errors during refactor. Static analysis is the safety net for moves the test suite does not see.

  • PHPArkitect or Deptrac enforces module boundaries. New cross-module imports break the build instead of slipping past review.

  • Rector automates large-scale renames, signature changes, and pattern migrations. You write a rule, it touches a thousand files, you review the diff.

  • Mutation testing with Infection on the legacy code confirms the test suite actually catches regressions before you start refactoring. If mutants survive, your tests are not pinning down behavior, and refactoring is risky.

The one thing to remember

Migration is incremental, opportunistic, and slow. New code in the new shape. Touched code cleaned up. Strategic refactors as projects. No big bangs. Nobody gets a rewrite budget.

The patterns from this course are a direction you move in, one PR at a time.

Course Content