How Composer Autoloading Works in PHP
Composer's autoloader maps namespaces to folders via PSR-4, so classes load automatically without manual require statements. Learn how it works and how to regenerate it.
Published September 18, 2026
Composer generates vendor/autoload.php, which registers an autoloader that loads class files on demand using the mappings in composer.json. You require that one file instead of dozens of includes.
The concept
When PHP meets an unknown class, it calls registered autoloaders with the class name. Composer's autoloader looks the name up in its generated maps and includes the right file.
The mappings come from composer.json: PSR-4 maps a namespace prefix to a directory, classmap scans folders, and files includes helper files on every request.
Lookup on first use
- Code runs new App\Services\Mailer()
- PHP has no such class, so it calls the Composer autoloader
- Autoloader matches prefix App\ → src/ and builds src/Services/Mailer.php
- The file is included and the class is available
Practical examples
PSR-4 in composer.json
{
"autoload": {
"psr-4": { "App\\": "src/" },
"files": ["src/helpers.php"]
}
}Entry point
require __DIR__ . '/vendor/autoload.php';Rebuild after changes
composer dump-autoload
composer dump-autoload -o # optimised classmap for productionCommon mistakes
- Editing composer.json and forgetting composer dump-autoload.
- Case mismatch between class name and file name on Linux.
- Forgetting the double backslash in JSON.
- Deploying without -o and running slower lookups.
Key takeaways
- Require vendor/autoload.php once.
- PSR-4 maps namespaces to folders.
- Run dump-autoload after changing mappings.
FAQ
What is the difference between psr-4 and classmap?
PSR-4 resolves by naming convention on demand; classmap scans folders and stores an exact map.
autoload vs autoload-dev?
autoload-dev holds test classes only needed in development.