Composer: managing dependencies in PHP projects
Every serious PHP project uses third-party code. Composer ensures that exactly the same versions run on the development machine, in testing and on the server — provided it is used correctly.
What you will learn
Two files, two jobs
`composer.json` describes what you want: which packages and within what range. `composer.lock` records what came out of it: each package with exactly one version and a checksum.
{ "require": { "php": ">=8.2", "monolog/monolog": "^3.5" }, "require-dev": { "phpunit/phpunit": "^11.0" } }For an application, both files belong in version control — the lock file too, especially that one. For libraries that others include as a package, it is often left out, because it has no effect for their users. It is the reason a colleague and the server get the same state as you.
You only confuse install and update once
A `composer update` on the server is an operation whose result nobody has seen beforehand. The same applies to `composer update` shortly before a release.
An example from practice
When the installation and the lock file diverge
A development tree in which `composer install` was never run after the lock file changed carries different package versions from those the project intends. The result is a pattern of errors that misleads: tests fail in bulk in an area nobody has touched.
That is why an automatic check is worthwhile, one that runs with every test run and reports exactly this — a comparison of the installed packages against the lock file. A cluster of errors in an area nobody has touched is a typical sign of deviating package versions and should therefore be checked against the lock file first; other causes are not ruled out by this.
What matters in operation
Common misconceptions
Further sources
- Composer: documentation the official manual
- Composer: versions and ranges what ^, ~ and * mean
- Packagist the directory of public packages
About the author
Fabian Lücker is managing partner of PHP-Schmiede KG in Rheine and has worked in software development since 2007. He is responsible for development and design and writes here about decisions that arise in real projects.