PHP "Class not found" - Fix Composer Autoload in CI
PHP could not locate a class because Composer’s generated autoloader does not map it. Usually the autoload files are stale, or the namespace-to-directory PSR-4 mapping in composer.json does not match where the file lives.
What this error means
Code that runs locally fails in CI with "Class X not found", even though the file exists. The class is yours (or from a package) but the autoloader’s classmap/PSR-4 prefix does not point at it.
PHP Fatal error: Uncaught Error: Class "App\Service\Mailer" not found in
/app/src/Controller/HomeController.php:18Common causes
Stale autoloader after adding files
A classmap-optimized autoloader was generated before a new class existed. Without regenerating, the new class is invisible.
PSR-4 namespace/path mismatch
The autoload.psr-4 prefix in composer.json does not match the namespace or the directory/case of the file, so the autoloader looks in the wrong place. Case matters on Linux runners even when it works on macOS.
How to fix it
Regenerate the autoloader
Rebuild Composer’s autoload files so new classes are mapped.
composer dump-autoload --optimize
# during install, this also runs:
composer install --no-interaction --optimize-autoloaderFix the PSR-4 mapping
Make the namespace prefix point at the directory the file actually lives in.
{
"autoload": {
"psr-4": { "App\\": "src/" }
}
}Check namespace and filename case
- Confirm the class’s
namespacematches the PSR-4 prefix exactly. - Confirm the file path and case match the namespace (Linux is case-sensitive).
- Run
composer dump-autoload -oand grep the generatedvendor/composer/autoload_classmap.phpfor the class.
How to prevent it
- Run
composer install --optimize-autoloaderin CI so the classmap is always fresh. - Keep PSR-4 prefixes and directory layout consistent, with correct case.
- Add a quick smoke check that autoloads core classes early in CI.