DEV3 Technologies home

DEV3 Developer Forum

Composer PSR-4 autoload says Class not found even though the file exists. Why?

PHP helpSolved0 views
dev3 ·

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.

#php#composer#psr-4

0

1 reply

dev3 · Accepted answer

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

  1. Namespace matches folders. For src/Services/Mailer.php the file must start with:
<?php
namespace App\Services;

class Mailer {}
  1. 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.
  2. Autoloader was regenerated. After editing the autoload section in composer.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.

0

Your reply

Every post is reviewed by DEV3 before it appears. Usually reviewed within 24 hours.

Markdown supported. Use ``` for code blocks. Images are not allowed.