PSR-4 autoloading: Composer's rule, explained

PSR-4 is the PHP-FIG autoloading standard, followed by Composer: a namespace prefix maps to a folder, and the rest of the class name gives the path of the file.

{
    "autoload": {
        "psr-4": {
            "Gazette\\": "src/"
        }
    }
}

With this declaration, Gazette\Article lives in src/Article.php, and Gazette\Contenu\Rubrique in src/Contenu/Rubrique.php: each level of the namespace after the prefix becomes a subfolder. The file name is exactly the class name, with the same case, followed by .php. In JSON, the backslash of the prefix is written twice, and the prefix ends with a backslash.

Composer applies this rule to your classes as well as to those of installed packages. It doesn't read composer.json again on every request: after changing the autoload section, you run composer dump-autoload. In production, composer dump-autoload -o turns the rule into a “class to file” map computed once and for all, faster to look up. Common mistakes: a namespace declared in the file that doesn't follow its folder (namespace Gazette; in src/Contenu/Rubrique.php), or a prefix without its final backslash.

2 exercises work on this concept, by writing code in the browser.

In the tracks

Related concepts

ComposerAutoloadNamespacesuse