PHP Composer Cheat Sheet
Explains Composer CLI commands, composer.json structure, semantic version constraints, and PSR-4 autoloading for PHP dependency management.
1 PageBeginnerApr 15, 2026
Composer CLI
Common commands for managing PHP dependencies.
bash
composer init # Interactively create composer.jsoncomposer require monolog/monolog # Add a dependency and install itcomposer require --dev phpunit/phpunit # Add a dev-only dependencycomposer install # Install exact versions from composer.lockcomposer update # Update deps within version constraintscomposer dump-autoload # Regenerate the autoloadercomposer show # List installed packages
composer.json
Core structure of a Composer manifest file.
json
{ "name": "acme/myapp", "require": { "php": "^8.2", "guzzlehttp/guzzle": "^7.8" }, "require-dev": { "phpunit/phpunit": "^10.0" }, "autoload": { "psr-4": { "App\\": "src/" } }}
Composer Concepts
Version constraints and autoloading fundamentals.
- ^7.8 (caret)- Allows updates that don't change the leftmost non-zero digit, e.g. >=7.8.0 <8.0.0
- ~7.8.0 (tilde)- Allows patch-level updates only when three components are given, e.g. >=7.8.0 <7.9.0
- composer.lock- Pins the exact resolved versions; commit it for applications to guarantee reproducible installs
- require vs require-dev- require-dev packages (tests, linters) are excluded when installing with --no-dev in production
- PSR-4 autoloading- Maps namespace prefixes to directories so classes load automatically without manual require statements
- vendor/ directory- Where Composer installs packages and generates the vendor/autoload.php bootstrap file
Using the Autoloader
Bootstrapping PSR-4 classes and file-based helpers.
php
// index.phprequire __DIR__ . '/vendor/autoload.php';use App\Models\Post;$post = new Post();// composer.json can also autoload plain files:// "autoload": {// "psr-4": { "App\\": "src/" },// "files": ["src/helpers.php"]// }
Pro Tip
Never hand-edit composer.lock without running composer install afterward to verify the resolved set actually installs cleanly — a stale or manually edited lock file can silently drift from composer.json.
Was this cheat sheet helpful?
Explore Topics
#PHPComposer#PHPComposerCheatSheet#Programming#Beginner#ComposerCLI#ComposerJson#ComposerConcepts#UsingTheAutoloader#CommandLine#CheatSheet#SkillVeris
Advertisement
Sri Hayavadhana Info-Tech
Professional Web Designing Services
- Responsive Websites
- E-commerce Solutions
- SEO Friendly Design
- Fast & Secure
- Support & Maintenance