Skip to content
Latchkey

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 error
PHP Fatal error:  Uncaught Error: Class "App\Service\Mailer" not found in
/app/src/Controller/HomeController.php:18

Common 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.

Terminal
composer dump-autoload --optimize
# during install, this also runs:
composer install --no-interaction --optimize-autoloader

Fix the PSR-4 mapping

Make the namespace prefix point at the directory the file actually lives in.

composer.json
{
  "autoload": {
    "psr-4": { "App\\": "src/" }
  }
}

Check namespace and filename case

  1. Confirm the class’s namespace matches the PSR-4 prefix exactly.
  2. Confirm the file path and case match the namespace (Linux is case-sensitive).
  3. Run composer dump-autoload -o and grep the generated vendor/composer/autoload_classmap.php for the class.

How to prevent it

  • Run composer install --optimize-autoloader in 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.

Related guides

Tired of flaky CI? Latchkey auto-heals failed jobs and retries them for you. Start free →