After Composer installs packages, it creates one file that makes every class available: vendor/autoload.php. You include it once.
<?php
require __DIR__ . "/vendor/autoload.php";
// every installed package, and your own classes, are now autoloaded
Put this line at the start of your front controller (usually public/index.php), and in command-line scripts. Use __DIR__ so the path is always right (see File Paths).
What the autoloader does
It registers one spl_autoload_register() function (see Autoloading). When your code uses a class, Composer’s autoloader finds the file from a map it generated when you ran composer install.
Autoload your own classes
Add an autoload section to composer.json:
{
"autoload": {
"psr-4": {
"App\\": "src/"
}
}
}
Then regenerate the autoloader:
composer dump-autoload
Now App\Service\Greeter is loaded from src/Service/Greeter.php automatically. PSR-4 Autoloading with Composer goes deeper.
When to run dump-autoload
- After you change the
autoloadsection ofcomposer.json. - After you add a class to a folder that is mapped with a classmap (not needed for PSR-4, where new files are found automatically).
For PSR-4, adding a new class file in the right folder with the right namespace is enough. You do not need to run anything.
Other autoload types
| Type | Use |
|---|---|
psr-4 | Standard for classes. Prefer this |
classmap | Scans folders and records every class. Useful for old code without namespaces |
files | Always loads certain files (helper functions) |
exclude-from-classmap | Ignore certain paths |
{
"autoload": {
"psr-4": { "App\\": "src/" },
"files": ["src/helpers.php"],
"classmap": ["legacy/"]
}
}
Optimised autoloader for production
composer install --no-dev --optimize-autoloader
or
composer dump-autoload --optimize
This builds a complete class map, so the autoloader does not search the file system. It is faster on a live server. In Composer’s own output, you will see a line such as “Generated optimized autoload files containing 397 classes”.
What lives in vendor/composer
vendor/composer/ holds the generated autoload files (autoload_psr4.php, autoload_classmap.php…). They are generated, so never edit them. They are rebuilt every time.
Common error: class not found
Class "App\Service\Greeter" not found usually means one of these:
vendor/autoload.phpwas never required.- The namespace in the file does not match the folder (check capitals).
- The
autoloadsection is missing or wrong incomposer.json. - You changed
composer.jsonand did not runcomposer dump-autoload.
One require
require "vendor/autoload.php". If you see many require lines for classes in a Composer project, something is wrong.