PHP › Namespaces & Autoloading
How does PSR-4 autoloading work, and how does it map a namespace structure directly to a corresponding directory structure on disk?
IntermediateAnswer
PSR-4 is a widely adopted autoloading standard that establishes a direct correspondence between a class's namespace and its physical file location, meaning a class named App\Services\Mailer, when properly configured, is automatically expected to exist at a file path like src/Services/Mailer.php relative to a base directory associated with the App namespace prefix, and Composer's autoloader uses this exact convention to automatically locate and load the correct file whenever a class is referenced, without any manual require statements.
// composer.json
{
"autoload": {
"psr-4": {"App\\": "src/"}
}
}
// App\Services\Mailer maps to src/Services/Mailer.phpReal-world example A developer adding a new Mailer class to the Services folder within their project's source directory can immediately use that class anywhere in the application without writing any require statement, since Composer's PSR-4 autoloader automatically knows exactly where to find it based purely on its namespace.