PSR-4 autoloading explained, with Composer examples and common errors
How PSR-4 maps namespaces to folders, how to configure it in composer.json, and why "Class not found" happens: case, typos, a stale autoloader or a namespace that does not match the path.
On this page
PSR-4 is the PHP-FIG standard that says how a fully qualified class name maps to a file path. Composer implements it, which is why you almost never write require statements in modern PHP.
The rule
Take a namespace prefix and map it to a base directory. Everything after the prefix becomes the path, with namespace separators turned into directory separators, plus .php.
| Prefix | Base directory | Class | File |
|---|---|---|---|
App\ |
src/ |
App\Http\Controller\HomeController |
src/Http/Controller/HomeController.php |
Acme\Billing\ |
lib/billing/ |
Acme\Billing\Invoice |
lib/billing/Invoice.php |
The prefix itself does not appear as a folder. That is the main difference from the older, now deprecated PSR-0, which used the full namespace as the path and treated underscores in class names as directory separators.
Configure it in composer.json
{
"autoload": {
"psr-4": {
"App\\": "src/"
}
},
"autoload-dev": {
"psr-4": {
"App\\Tests\\": "tests/"
}
}
}
Backslashes are escaped in JSON, and the prefix ends with \\. After any change to these sections, regenerate the autoloader:
composer dump-autoload
Why “Class not found”
1. Case does not match. App\Http\homeController will load from homeController.php on macOS (case-insensitive disk) and fail on Linux. Match the case of the class and the file exactly.
2. Namespace does not match the folder. A file at src/Service/Mailer.php must declare namespace App\Service;. Composer warns about this: “Class App\Mailer located in ./src/Service/Mailer.php does not comply with psr-4 autoloading standard. Skipping.” Since Composer 2, non-compliant classes are skipped from the optimized class map.
3. One class per file, file named after the class. PSR-4 cannot find two classes in one file.
4. The autoloader is stale. If you deploy with --optimize-autoloader or --classmap-authoritative, new files are not found until the class map is rebuilt. Run composer dump-autoload -o as part of the deploy.
5. Missing use statement. new Mailer() inside namespace App\Http; looks for App\Http\Mailer. Import it with use App\Service\Mailer;.
Functions and constants
PSR-4 only autoloads classes, interfaces, traits and enums. For a file of helper functions, use Composer’s files autoload:
"autoload": {
"psr-4": { "App\\": "src/" },
"files": ["src/helpers.php"]
}
Speed in production
composer install --no-dev --optimize-autoloader
# or, if every class is known at build time:
composer install --no-dev --classmap-authoritative
The optimized class map avoids file-system lookups. With APCu available, --apcu-autoloader caches lookups too.