How to Use PSR-4 Autoloading in PHP: Simple Guide
To use
PSR-4 autoloading in PHP, define a namespace-to-directory mapping in your composer.json file under the autoload section, then run composer dump-autoload. This lets PHP automatically load classes based on their namespaces without manual require statements.Syntax
The PSR-4 autoloading syntax is defined in the composer.json file under the autoload key. It maps a namespace prefix to a directory path where class files live.
- Namespace prefix: The root namespace your classes use.
- Directory path: The folder where the classes for that namespace are stored.
Composer uses this mapping to find and load classes automatically.
json
{
"autoload": {
"psr-4": {
"MyApp\\": "src/"
}
}
}Example
This example shows how to set up PSR-4 autoloading with Composer, create a class in the mapped namespace, and use it without manual includes.
php
// composer.json { "autoload": { "psr-4": { "MyApp\\": "src/" } } } // src/Greeting.php <?php namespace MyApp; class Greeting { public function sayHello(): string { return "Hello, PSR-4!"; } } // test.php <?php require __DIR__ . '/vendor/autoload.php'; use MyApp\Greeting; $greet = new Greeting(); echo $greet->sayHello();
Output
Hello, PSR-4!
Common Pitfalls
Common mistakes when using PSR-4 autoloading include:
- Not running
composer dump-autoloadafter changingcomposer.json. - Incorrect namespace or directory mapping causing classes not to load.
- Class files not matching the namespace and class name structure (file path must match namespace and class name).
- Forgetting to include Composer's
vendor/autoload.phpfile.
php
// Wrong: Namespace does not match directory structure // src/Greeting.php <?php namespace WrongNamespace; class Greeting {} // Right: Namespace matches directory // src/Greeting.php <?php namespace MyApp; class Greeting {}
Quick Reference
Tips for using PSR-4 autoloading:
- Namespace prefixes end with a backslash
\\. - Directory paths are relative to
composer.json. - Class files must be named exactly as the class with
.phpextension. - Run
composer dump-autoloadafter changes. - Always include
vendor/autoload.phpin your entry script.
Key Takeaways
Define namespace-to-directory mapping in composer.json under autoload > psr-4.
Class file paths must match their namespaces exactly for autoloading to work.
Run composer dump-autoload after editing composer.json to update autoload files.
Include vendor/autoload.php in your PHP scripts to enable autoloading.
PSR-4 autoloading removes the need for manual require/include statements.