Legacy Bridge
Last updated: 2026-11-03
Most PHP legacy codebases don't get rewritten — they get inherited. Canvas lets you introduce modern architecture incrementally, without breaking URLs, without a flag day, and without freezing feature development.
Enable Legacy Support
Point Canvas at your existing PHP files and it handles the rest:
// config/app.php
return [
'legacy_enabled' => true,
'legacy_path' => dirname(__FILE__) . "/../legacy"
]; From this point, every URL your application currently serves continues to work. Nothing breaks. You now have a foundation to build on.
Route Fallthrough
Canvas checks its own routes first. If no Canvas route matches, it falls back to the legacy filesystem:
URL: /admin/users
1. Check Canvas routes → Not found
2. Load legacy/admin/users.php → Executes
3. Canvas services available via canvas() helper
This means you can migrate routes one at a time. Once you create a Canvas controller for a given URL, it takes precedence. The legacy file remains untouched as a fallback until you're ready to remove it.
How Canvas Finds Legacy Files
Canvas uses file resolvers to map URLs to filesystem paths. Resolvers are tried in order; the first one that returns a path wins.
Default File Resolver
The DefaultFileResolver is registered automatically when legacy support is enabled. It handles the most common URL-to-file mapping patterns:
- URL Normalization: Removes leading/trailing slashes
- Direct .php Requests: URLs ending in
.phpmap directly to filesystem paths - Pattern Matching: For all other URLs, tries multiple file patterns in order
For a request to /admin/users, the resolver checks in order:
1. Direct file: legacy/admin/users.php
2. Index file: legacy/admin/users/index.php The first matching readable file is used. If nothing matches, Canvas returns a 404.
Examples
// Direct file
URL: /admin/dashboard → legacy/admin/dashboard.php
// Directory with index
URL: /admin/users → legacy/admin/users/index.php
// Explicit .php request
URL: /admin/script.php → legacy/admin/script.php
// Root
URL: / → legacy/index.php Custom File Resolvers
Real legacy codebases rarely follow clean conventions. Canvas ships a second resolver, WordPressStyleResolver, for date-based permalinks out of the box; for anything else — non-standard file organization, a different permalink scheme, or any other custom URL shape — implement your own.
Configuring Resolvers
Resolvers are tried in the order listed, and the first one that returns a path wins. By default that's just DefaultFileResolver; add others with legacy_resolvers. Each class is built with legacy_path passed as its legacyPath constructor argument; any other constructor parameter is autowired through the DI container, the same as controllers and aspects:
// config/app.php
use Quellabs\Canvas\Legacy\Resolvers\DefaultFileResolver;
use Quellabs\Canvas\Legacy\Resolvers\WordPressStyleResolver;
return [
'legacy_enabled' => true,
'legacy_path' => dirname(__FILE__) . "/../legacy",
'legacy_resolvers' => [WordPressStyleResolver::class, DefaultFileResolver::class]
]; WordPressStyleResolver maps /YYYY/MM/post-slug URLs to legacy/posts/YYYY-MM-post-slug.php. Put specific resolvers like this one before DefaultFileResolver, which acts as the catch-all.
A resolver class that doesn't exist, or doesn't implement FileResolverInterface, throws an InvalidArgumentException immediately rather than silently resolving nothing.
Writing a Custom Resolver
Implement FileResolverInterface directly for a URL scheme the built-in resolvers don't cover:
// src/Legacy/CustomFileResolver.php
namespace App\Legacy;
use Quellabs\Canvas\Legacy\FileResolverInterface;
use Symfony\Component\HttpFoundation\Request;
class CustomFileResolver implements FileResolverInterface {
public function __construct(private string $legacyPath) {}
public function resolve(string $path, Request $request): ?string {
// Return absolute file path if found, null to pass to next resolver
}
} Example — date-based article URLs:
public function resolve(string $path, Request $request): ?string {
if (preg_match('#^/(\d{4})/(\d{2})/(.+)$#', $path, $matches)) {
$year = $matches[1];
$month = $matches[2];
$slug = $matches[3];
return $this->legacyPath . "/articles/{$year}/{$month}/{$slug}.php";
}
return null;
} Add it to legacy_resolvers alongside the built-in ones, in whatever order matches your URL schemes:
'legacy_resolvers' => [App\Legacy\CustomFileResolver::class, DefaultFileResolver::class] Resolvers With Injected Dependencies
A resolver isn't limited to legacyPath — add any other typed constructor parameter and Canvas autowires it from the DI container, exactly as it would for a controller:
namespace App\Legacy;
use App\Repositories\RedirectMapRepository;
use Quellabs\Canvas\Legacy\FileResolverInterface;
use Symfony\Component\HttpFoundation\Request;
class DatabaseBackedResolver implements FileResolverInterface {
public function __construct(
private string $legacyPath,
private RedirectMapRepository $redirects
) {}
public function resolve(string $path, Request $request): ?string {
$slug = $this->redirects->findLegacySlugFor($path);
return $slug !== null ? $this->legacyPath . "/posts/{$slug}.php" : null;
}
} Every class in legacy_resolvers is autowired through the container, so a resolver declares its dependencies exactly like a controller does.
Using Canvas Services in Legacy Files
Once the Legacy Bridge is active, your existing PHP files gain access to Canvas services without any structural changes to those files:
// legacy/admin/dashboard.php
use Quellabs\Canvas\Legacy\LegacyBridge;
// Via global helper — canvas() returns the DI container
$users = canvas()->get(EntityManager::class)->findBy(User::class, ['active' => true]);
// Via LegacyBridge directly
$em = LegacyBridge::container()->get(EntityManager::class);
$users = $em->findBy(User::class, ['active' => true]); This is typically the first thing you'll use. Before migrating a single route, you can start replacing raw SQL queries and procedural logic with Canvas services inside your existing files.
canvas() accepts an optional DI context (a string or array, as accepted by Container::for()) to scope resolution before calling get():
$cache = canvas('redis')->get(CacheInterface::class); Legacy Preprocessing
Legacy PHP files frequently use header(), die(), and exit() in ways that would short-circuit Canvas's request/response lifecycle. Preprocessing intercepts these calls and converts them to Canvas-compatible equivalents before execution.
Preprocessing is enabled by default:
// config/app.php
return [
'legacy_enabled' => true,
'legacy_path' => dirname(__FILE__) . "/../legacy",
'legacy_preprocessing' => true // Default
]; What Gets Transformed
- Header calls:
header()converts to Canvas header management - Response codes:
http_response_code()converts to Canvas response code management - Exits:
die()andexit()convert to Canvas exceptions - Database calls:
mysqli_query(),mysqli_prepare(), andnew PDO()convert to monitored equivalents (see below)
// Original legacy code — works as-is after preprocessing
header('Content-Type: application/json');
http_response_code(201);
echo json_encode(['data' => $data]);
die(); Recursive Preprocessing
Preprocessing follows your file's entire include tree. Canvas discovers all include and require statements, preprocesses each dependency, rewrites include paths to point at preprocessed versions, and caches the results.
// legacy/main.php
header('Content-Type: text/html'); // Converted
include 'includes/helper.php'; // Also preprocessed
// legacy/includes/helper.php
header('Location: /redirect'); // Also converted
die('Stopping execution'); // Also converted Database Call Monitoring
Preprocessing also rewrites mysqli_query(), mysqli_prepare(), and new PDO() to monitored equivalents that feed query text, bound parameters, and execution time to the Inspector.
// Original legacy code
$result = mysqli_query($connection, "SELECT * FROM users");
$pdo = new PDO($dsn, $user, $pass);
$stmt = $pdo->prepare("SELECT * FROM posts WHERE id = ?"); The objects these calls return are real mysqli_stmt/PDO/PDOStatement subclasses, not lookalike wrappers — so existing code that does $pdo instanceof PDO, or type-hints a parameter as PDO, PDOStatement, or mysqli_stmt, keeps working unchanged after preprocessing.
Excluding Vendored Libraries
Preprocessing is meant for your legacy code — the files that call header(), die(), or run raw queries. A third-party library you've vendored alongside your legacy files (a bundled mailer, a PDF generator, anything under its own vendor/ directory) doesn't need any of that rewriting, and running regex-based transforms over code you didn't write is both unnecessary and risky.
Any path with a vendor/ segment is always skipped, with no configuration needed. For a vendored library kept outside vendor/, list its path in exclusion_paths:
// config/app.php
return [
'legacy_enabled' => true,
'legacy_path' => dirname(__FILE__) . "/../legacy",
'exclusion_paths' => ['libs/third-party']
]; A path matches when it appears as one or more whole path segments — excluding lib matches legacy/lib/anything.php but not an unrelated file like calibrate.php.
Limitations
Preprocessing works with static include paths. Three edge cases to be aware of:
- Dynamic includes —
include $dynamicPathcannot be detected at preprocessing time. Files included this way will not be preprocessed. If those files containheader()ordie()calls, handle them manually or refactor the dynamic path to be static. - Conditional includes — Files inside conditionals are preprocessed regardless of whether the condition would have prevented execution. This is safe in most cases but worth knowing if you have environment-specific includes.
- Deep include trees — Initial preprocessing of a deeply nested file tree can be slow. Results are cached after the first run.
Disabling Preprocessing
Turn it off if your legacy files don't use header(), die(), or exit(), or when debugging a preprocessing issue:
// config/app.php
return [
'legacy_enabled' => true,
'legacy_path' => dirname(__FILE__) . "/../legacy",
'legacy_preprocessing' => false
]; Clearing the Cache
Clear the preprocessing cache after modifying legacy files during development:
// Programmatically
$kernel->getLegacyHandler()->clearCache();
// Via Sculpt
php sculpt legacy:clear-cache Custom Error Pages
Place error pages in your legacy directory and Canvas will use them automatically:
// legacy/404.php
<!DOCTYPE html>
<html>
<body>
<h1>404 - Page Not Found</h1>
<p><a href="/">Return to Homepage</a></p>
</body>
</html> Canvas looks for 404.php (no matching file) and 500.php (execution failure). If neither exists, Canvas's default error pages are used.
Migration Path
There is no required migration timeline. The four phases below represent a natural progression, but you can stay in any phase as long as needed — or move between them non-linearly as your codebase allows.
Phase 1: Enable Legacy Support
Drop Canvas in as the front controller. Everything continues to work. Start accessing Canvas services from legacy files.
// config/app.php
return [
'legacy_enabled' => true,
'legacy_path' => dirname(__FILE__) . "/../legacy"
]; All existing URLs still work. Canvas services are now available in legacy files:
// legacy/admin/dashboard.php
$users = canvas()->get(EntityManager::class)->findBy(User::class, ['active' => true]); Phase 2: Build New Features with Canvas
New functionality goes into Canvas controllers from day one. Legacy code handles everything else.
class ApiController extends BaseController {
/**
* @Route("/api/users", methods={"GET"})
*/
public function users() {
return $this->json($this->em()->findBy(User::class, []));
}
} Phase 3: Migrate Legacy Routes Incrementally
Convert legacy files to Canvas controllers one route at a time. Because Canvas routes take precedence over legacy files, you can migrate a route and keep the legacy file in place until you're confident:
// Before: legacy/admin/users.php
// After: src/Controllers/AdminController.php
/**
* @Route("/admin/users", methods={"GET"})
*/
public function users() {
$users = $this->em()->findBy(User::class, ['active' => true]);
return $this->render('admin/users.tpl', compact('users'));
} Phase 4: Remove Legacy Support
Once all routes are migrated, disable legacy support entirely:
// config/app.php
return [
'legacy_enabled' => false
]; Frequently Asked Questions
Does the Legacy Bridge require changes to my existing PHP files?
No. Point Canvas at your legacy directory and every existing URL keeps working as-is. Preprocessing handles header(), http_response_code(), die(), and exit() calls automatically, so legacy files don't need to be rewritten to run safely inside Canvas's request/response lifecycle.
Can I use Canvas services before migrating any routes?
Yes — this is usually the first step. Legacy files get access to Canvas services like the EntityManager through the canvas() helper (canvas()->get(EntityManager::class)) or LegacyBridge::container() directly, so you can start replacing raw SQL and procedural logic with Canvas services long before any route is converted to a Canvas controller.
What happens to a legacy file after I migrate its route to a Canvas controller?
It stays in place and is simply no longer reached. Canvas checks its own routes first, so once a matching Canvas controller exists, requests go there instead; the legacy file remains as an untouched fallback until you choose to delete it.
Does the Legacy Bridge work with non-standard URL structures, like WordPress permalinks?
Yes. Canvas ships a WordPressStyleResolver for date-based permalinks — add it to legacy_resolvers in config/app.php. For any other custom scheme, implement FileResolverInterface yourself and add that class to legacy_resolvers too; the built-in DefaultFileResolver keeps handling conventional URL-to-file mapping as the catch-all at the end of the list.
Is there a deadline to finish migrating, or a required order?
No. The four phases above are a natural progression, not a mandatory timeline — you can stay in any phase indefinitely, or move between them non-linearly as your codebase and priorities allow.
Will preprocessing catch every header() or die() call in my legacy code?
It catches every statically included file in the include tree. Dynamic includes (include $variablePath) can't be detected at preprocessing time, so header() or die() calls inside those files need to be handled manually or the include path refactored to be static.
Will preprocessing rewrite third-party libraries I've vendored alongside my legacy code?
No. Any path with a vendor/ segment is always skipped, and exclusion_paths can exclude vendored code kept elsewhere. Third-party libraries don't need header()/die() interception or database-call monitoring, and running the preprocessor's transforms over code you didn't write is unnecessary risk.
If legacy code checks $pdo instanceof PDO, will preprocessing break it?
No. The monitored PDO, PDOStatement, and mysqli_stmt objects preprocessing substitutes in are real subclasses of the native classes, not lookalike wrappers, so instanceof checks and type-hinted parameters against the native classes keep working after a database call is rewritten.