PHP 7: Maintaining and Upgrading Legacy Apps · Refactoring Legacy PHP Safely

The Strangler Fig Pattern

Replace a legacy app piece by piece behind a routing layer.

The strangler fig pattern places a routing layer (Nginx, a front controller, or a modern framework) in front of the legacy app. New or rewritten features are served by new code; everything else falls through to the old app. Over time, routes migrate until the legacy code can be removed. Share sessions/auth between both during the transition.

# Nginx: new routes go to the Symfony/Laravel app, everything else to legacy
location ^~ /api/v2/ {
    try_files $uri /new/index.php$is_args$args;
}
location ^~ /checkout/ {
    try_files $uri /new/index.php$is_args$args;
}
location / {
    try_files $uri $uri/ /legacy/index.php$is_args$args;
}

Alternatively, a modern framework can be the front controller and forward unknown routes to legacy scripts via a fallback controller (e.g., a "legacy bridge" that requires the old file inside output buffering).

Common pitfalls

  • Two apps with different session formats, forcing users to log in twice.
  • No plan to delete legacy routes after migration.
  • Duplicating business rules in old and new code that drift apart.

Key points

  • Route new features to new code
  • Migrate route by route
  • Share auth/session; delete old code when done

Further reading: Martin Fowler: Strangler Fig

Practice questions

What's the main advantage of the strangler fig over a rewrite?

Answer

Value ships continuously and risk is limited to each migrated slice; the legacy app keeps working until each part is replaced.

What shared concern is hardest during strangling?

Answer

Authentication and sessions (and sometimes the database schema), since both apps must recognize the same logged-in user and data.

Open in the app to mark lessons complete, take notes and track your progress.