PSR-4 autoloading

PSR-4 is the rule that turns a class name into a file path, and PHP projects hand the rule to Composer. The example below is a whole project in three files, and every command on the page was run on it.

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.

The map lives in composer.json:

{ "name": "acme/demo", "version": "1.0.0", "autoload": { "psr-4": { "Acme\\Demo\\": "src/" } } }

The class file src/User.php carries the namespace of the prefix:

<?php namespace Acme\Demo; class User { public function name(): string { return "Ann"; } }

The page that never requires the class by hand, index.php:

<?php require "vendor/autoload.php"; $user = new Acme\Demo\User(); echo get_class($user), PHP_EOL; echo $user->name(), PHP_EOL;

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

Generating autoload files
Generated autoload files

With the autoloader written, the page of the first section runs:

php index.php

Acme\Demo\User
Ann

The class name went through the map into src/User.php, and no file of the project required it by hand.

composer dump-autoload -o

Generating optimized autoload files
Generated optimized autoload files containing 2 classes

The optimized form also counts the classes it found, which is why the flag is popular in production.

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"] } }

Exercises

  1. Add a Post class with the same prefix and load it without a require.
  2. Add a second prefix that points at lib/ and load a class from it.
  3. Nest a namespace one level deeper and find the folder the file must live in.
  4. Run composer dump-autoload -o and read the class count it reports.
  5. Break the case of a folder name and describe the error on a case sensitive system.

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. What does PSR-4 map?

    Answer

    A namespace prefix to a base folder

    The prefix is stripped from the class name and the rest of the name becomes the path inside the base folder.

  2. Which file does a PSR-4 page require once?

    Answer

    vendor/autoload.php

    The generated autoloader registers the map, so one require serves every class of the project and its packages.

  3. When must composer dump-autoload run again?

    Answer

    After adding a class or changing an autoload rule

    The dump writes the maps, so a new class or a new prefix has to be recorded before it can load.

  4. What does composer dump-autoload -o add?

    Answer

    A class map built ahead of time, so lookups need no filesystem checks

    The optimized dump scans the classes once and writes a map, which is why it reports how many it found.

  5. What does this program print? <?php $class = "Acme\\Demo\\User"; $prefix = "Acme\\Demo\\"; $path = "src/" . str_replace("\\", "/", substr($class, strlen($prefix))) . ".php"; echo $path;

    Answer

    src/User.php

    The prefix is cut off first, and only the rest of the name becomes the path inside src/.

  6. What does this program print? <?php $class = "Shop\\Cart\\Item"; $prefix = "Shop\\"; $path = "app/" . str_replace("\\", "/", substr($class, strlen($prefix))) . ".php"; echo $path;

    Answer

    app/Cart/Item.php

    Everything after the prefix keeps its separators as folders, so the nested namespace lands in app/Cart/.

  7. What does this program print? <?php $prefixes = ["Acme\\Demo\\" => "src/", "Shop\\" => "app/"]; $class = "Shop\\Cart"; $path = "none"; foreach ($prefixes as $prefix => $dir) { if (str_starts_with($class, $prefix)) { $path = $dir . str_replace("\\", "/", substr($class, strlen($prefix))) . ".php"; break; } } echo $path;

    Answer

    app/Cart.php

    Only the Shop prefix matches, so the class takes the app/ folder and the rest of the name is Cart.

  8. What does this program print? <?php $class = "Acme\\Demo\\User"; $prefix = "Acme\\Demo\\"; echo str_starts_with($class, $prefix) ? "mapped" : "no";

    Answer

    mapped

    The class name begins with the prefix, which is the first test every PSR-4 loader makes.

  9. What does this composer.json tell the autoloader? { "autoload": { "psr-4": { "Shop\": "app/" } } }

    Answer

    Classes under Shop\ start in the folder app/

    Only names that begin with the prefix take the folder, and the rest of the name is the rest of the path.

  10. Why must the file name match the class name exactly?

    Answer

    Because the autoloader builds the path from the class name

    A mismatch means the computed path points at a file that does not exist, and the class is not found.

The project on this page was run with PHP 8.5.13 (php -v) and Composer 2.10.3 in Alpine Linux, with the commands shown above.

Article author: Arthur Isaev