PSR-4 is a PHP standard recommendation that provides guidelines for autoloading classes from file paths. It is managed by the PHP-FIG (PHP Framework Interop Group) and defines a way to map the fully qualified class names to the corresponding file paths. This standard helps streamline class loading, especially in larger projects and frameworks.
Namespace Mapping: PSR-4 requires that the namespace and class name match the directory structure and file name. Each namespace prefix is associated with a base directory, and within that directory, the namespace hierarchy corresponds directly to the directory structure.
Base Directory: For each namespace prefix, a base directory is defined. Classes within that namespace are located in subdirectories of the base directory according to their namespace structure. For example:
App\Controllers
, the file would be located in a folder like /path/to/project/src/Controllers
.File Naming: The class name must match the filename exactly, including case sensitivity, and end with .php
.
Autoloader Compatibility: Implementing PSR-4 ensures compatibility with modern autoloaders like Composer’s, allowing PHP to locate and include classes automatically without manual require
or include
statements.
Suppose you have the namespace App\Controllers\UserController
. According to PSR-4, the directory structure would look like:
/path/to/project/src/Controllers/UserController.php
In Composer’s composer.json
, this mapping is specified like so:
{
"autoload": {
"psr-4": {
"App\\": "src/"
}
}
}
This configuration tells Composer to load classes in the App
namespace from the src/
directory. When you run composer dump-autoload
, it sets up the autoloading structure to follow PSR-4 standards.
PSR-4 has replaced the older PSR-0 standard, which had more restrictive rules on directory structure, making PSR-4 the preferred autoloading standard for modern PHP projects.