PSR-4 autoloading
| Namespace to path | |
| composer dump-autoload | |
| Classmap fallback | |
| Files autoload |
Namespace to path
PSR-4 turns a class name into a file path by replacing separators with folder dividers. The prefix maps to one base folder, the rest points deeper inside.
Keep one class per file and match file names to class names exactly for reliable loading.
require "vendor/autoload.php"; $user = new Acme\Demo\User(); echo get_class($user);
composer dump-autoload
Composer builds optimized maps from the current config. Run the dump command after adding classes or editing autoload rules.
Production builds often add the optimized flag, while local work uses the plain command for speed.
composer dump-autoload
Generated autoload files.
Classmap fallback
Classmap scans folders and records every class file it finds. It fits legacy code where file layout does not follow PSR-4 rules.
List only folders that need scanning, since wide scans slow down every dump.
{ "autoload": { "classmap": ["src/", "lib/"] } }
Files autoload
Files loading includes given scripts on every request. It suits global helpers that must exist before any class runs.
Keep these files small and free of side effects beyond function definitions.
{ "autoload": { "files": ["src/helpers.php"] } }
Next: PDO transactions
Article author: Arthur Isaev