PHP 7: Maintaining and Upgrading Legacy Apps · Working in a Legacy PHP Codebase
Introducing Composer to a Legacy Project
Add Composer and autoloading without breaking existing includes.
Many legacy apps predate Composer and rely on require_once chains. Introduce Composer incrementally: create composer.json, require vendor/autoload.php in the bootstrap, use a classmap autoloader for existing non-PSR-4 class files, and put new code under a PSR-4 namespace. Libraries you previously copied into the repo can be replaced with Composer packages one at a time.
{
"require": { "php": ">=7.4" },
"autoload": {
"classmap": ["lib/", "classes/"],
"psr-4": { "App\\": "src/" },
"files": ["lib/helpers.php"]
},
"config": { "platform": { "php": "7.4.33" } }
}
Setting config.platform.php makes Composer resolve dependencies compatible with the production PHP version, even if your laptop runs PHP 8.
Common pitfalls
- Installing packages that require PHP 8 while production runs 7.4 (set
config.platform.php). - Removing
require_oncelines before the autoloader covers those classes. - Committing
vendor/instead ofcomposer.lock.
Key points
- Classmap for legacy classes, PSR-4 for new code
- Pin the platform PHP version
- Migrate vendored libraries gradually
Further reading: Composer: autoload schema
Practice questions
Why set config.platform.php in a legacy project?
Answer
So Composer only installs package versions compatible with the production PHP version, regardless of the PHP version used on the developer's machine.
How can Composer autoload classes that don't follow PSR-4?
Answer
With the classmap autoloader, which scans directories and maps each class to its file, regardless of naming conventions.
Open in the app to mark lessons complete, take notes and track your progress.