I set "autoload": {"psr-4": {"App\": "src/"}} and created src/Services/Mailer.php with class Mailer, but new App\Services\Mailer gives 'Class not found'. I ran composer install.
DEV3 Developer Forum
Composer PSR-4 autoload says Class not found even though the file exists. Why?
Every post is reviewed first. Usually reviewed within 24 hours.
1 reply
PSR-4 maps a namespace prefix to a directory, and the rest of the class name must match the file path exactly, including case.
Checklist
- Namespace matches folders. For
src/Services/Mailer.phpthe file must start with:
<?php
namespace App\Services;
class Mailer {}
- Class name equals file name, same case (
Mailer.php). It works on Windows and macOS (case-insensitive) and fails on Linux servers, which is why it works locally and breaks in production. - Autoloader was regenerated. After editing the
autoloadsection incomposer.json, run:
composer dump-autoload
Installing packages does not pick up your changed mapping unless the autoloader is rebuilt.
4. You include vendor/autoload.php once at the entry point: require __DIR__.'/vendor/autoload.php';.
5. JSON escaping. In composer.json the backslash is doubled, and the trailing one is required:
{
"autoload": {
"psr-4": { "App\\": "src/" }
}
}
"App": "src/" (no trailing backslashes) does not match.
6. Optimized authoritative classmap. If you deployed with --classmap-authoritative, new classes not present when the map was built are not found. Rebuild during deploy.
7. One class per file and no declare mistakes: a syntax error in the file makes the class fail to load with a different error, check the PHP log.
Debug
composer dump-autoload -o
php -r 'require "vendor/autoload.php"; var_dump(class_exists("App\\Services\\Mailer"));'
You can also inspect vendor/composer/autoload_psr4.php to see the registered prefixes.
Tip: use composer dump-autoload -o --strict-psr (Composer 2.4+) to fail the build and list classes that violate PSR-4 rules.