Autoloading and PSR-4

6.Autoloading and PSR-4

M

In this chapter

We'll learn how autoloading replaces dozens of require_once lines — spl_autoload_register(), the PSR-4 standard that maps namespaces to folders, Composer's vendor/autoload.php, the capital-letter bug that only appears on Linux, classmaps and optimised autoloaders for production, files autoloading for plain functions, and where the older PSR-0 came from.

17–19 min

The Problem in Real Life

bin/send-reminders.php starts with fourteen require_once lines, one per class file. Mia created BookingStatus.php yesterday and forgot to add the fifteenth. On her laptop the page that loads it happened to run first; on the server, the reminder script dies: "Class "BookBay\Booking\BookingStatus" not found".

Meanwhile the TextFlow package and the phone-number library load dozens of their own classes, and nobody wrote a single require for any of them.

M

How does Composer know which file each of their classes is in? And can it do that for ours?

Mia

A require_once per File vs. Loading Classes on Demand

Lists that go stale

Every new class means updating require lines in every script that might need it.

Load when first used

An autoloader is a function PHP calls the moment it meets a class it doesn't know yet.

Namespace = folder

PSR-4 turns BookBay\Booking\Booking into src/Booking/Booking.php — no list needed.

Autoloading and PSR-4

Classes that load themselves: Act 10 loaded files with require_once. For classes, PHP has something better: it can ask your code to load a class at the exact moment it's needed. This chapter covers:

  • spl_autoload_register(): how autoloading works inside PHP.
  • PSR-4: the standard rule that maps a namespace to a folder.
  • vendor/autoload.php: Composer's autoloader for everything.
  • Classmap and optimisation: faster loading in production.
  • files autoloading and PSR-0: plain functions, and the history.

spl_autoload_register(): when PHP meets a class, interface, trait or enum it doesn't know yet — in new, a static call, instanceof, a type check, class_exists() — it calls every function registered with spl_autoload_register(), passing the fully qualified class name as a string. The function's job is to require the right file; if afterwards the class exists, PHP carries on as if it had always been there. If no autoloader finds it, you get "Class … not found". Autoloading is lazy: a class that's never used is never loaded, so a script that sends reminders doesn't load the code for invoices. Functions and constants are not autoloaded — only class-like names. The first example below is a tiny autoloader that you can run in the Playground; it shows the name PHP passes in and the file it would load.

A tiny autoloader: PHP passes the full class name
<?php
namespace BookBay\Booking;
spl_autoload_register(function (string $class): void {
$prefix = 'BookBay\\';
$relative = substr($class, strlen($prefix)); // Booking\BookingStatus
$file = '/app/src/' . str_replace('\\', '/', $relative) . '.php';
echo "autoloader asked for {$class}\n";
echo " would load {$file}\n";
if (is_file($file)) {
require $file;
}
});
var_dump(class_exists(BookingStatus::class)); // calls the autoloader; no file here, so false
var_dump(class_exists(BookingStatus::class, false)); // false, and no message: false = "don't autoload"
// autoloader asked for BookBay\Booking\BookingStatus
// would load /app/src/Booking/BookingStatus.php
// bool(false)
// bool(false)

PSR-4: one rule instead of a list: an autoloader needs a rule to turn a class name into a file name. PSR-4 is the standard rule, published by the PHP-FIG (the PHP Framework Interop Group, which also writes the PSR-12 coding style from Act 02). It maps a namespace prefix to a base folder: with "BookBay\\": "src/", the class BookBay\Booking\BookingStatus loses the prefix BookBay\, the rest becomes a path — Booking\BookingStatus → Booking/BookingStatus — and .php is added: src/Booking/BookingStatus.php. Each sub-namespace is a folder and each class is a file with exactly the class's name. Once that's true, a new class needs no extra line anywhere. The diagram below follows one class name to its file.

PSR-4: from a class name to a file

new BookingStatus(…)

resolved to BookBay\Booking\BookingStatus (chapter 3)

PHP doesn't know the class yet

Autoloader called

with "BookBay\Booking\BookingStatus"

split the name

Prefix BookBay\ → src/

from "autoload": { "psr-4": { "BookBay\\": "src/" } }

Rest: Booking\BookingStatus

\ → / plus .php

load

require src/Booking/BookingStatus.php

the class now exists

vendor/autoload.php: you write the PSR-4 rule in composer.json under autoload, run composer dump-autoload once (Composer also does it after every install or update), and add one line to every entry script: require __DIR__ . '/../vendor/autoload.php';. That file registers Composer's autoloader, which knows your rule and every package's rule — the generated file vendor/composer/autoload_psr4.php lists them all. Fourteen require_once lines become one, and a class created tomorrow just works. Composer prefers the longest matching prefix, so a package with BookBay\Pricing\ (chapter 9) can live next to the project's BookBay\. Use autoload-dev for classes only needed in development, like tests (Act 21).

PSR-4 in composer.json, and the one require
// ---- composer.json (part) ----
{
"autoload": {
"psr-4": {
"BookBay\\": "src/"
},
"files": [
"src/helpers.php"
]
}
}
// ---- bin/send-reminders.php ----
<?php
declare(strict_types=1);
require __DIR__ . '/../vendor/autoload.php'; // the only require in the project
use BookBay\Booking\Booking; // → src/Booking/Booking.php
use BookBay\Booking\BookingStatus; // → src/Booking/BookingStatus.php
use BookBay\Notifications\Notification; // → src/Notifications/Notification.php
What Composer generated: vendor/composer/autoload_psr4.php
<?php
// autoload_psr4.php @generated by Composer
$vendorDir = dirname(__DIR__);
$baseDir = dirname($vendorDir);
return array(
'libphonenumber\\' => array($vendorDir . '/giggsey/libphonenumber-for-php-lite/src'),
'Symfony\\Polyfill\\Mbstring\\' => array($vendorDir . '/symfony/polyfill-mbstring'),
'BookBay\\Pricing\\' => array($vendorDir . '/bookbay/pricing/src'),
'BookBay\\' => array($baseDir . '/src'),
);

The capital-letter bug: Mia's laptop runs macOS, where file names are case-insensitive by default — so is Windows. If a class BookBay\Notifications\SmsSender lives in src/Notifications/Smssender.php, it loads fine there, because SmsSender.php and Smssender.php are the same file. The Linux server's file system is case-sensitive: there they're different names, and the class is "not found" — only in production. The rule: file and folder names must match the namespace and class name letter for letter. composer dump-autoload -o warns about every file that breaks the rule, as the example below shows; running it in CI catches the bug before the server does.

Real output: Composer catches the capital-letter bug
$ composer dump-autoload -o
Generating optimized autoload files
Class BookBay\Notifications\SmsSender located in ./src/Notifications/Smssender.php does not comply with psr-4 autoloading standard (rule: BookBay\ => ./src). Skipping.
Generated optimized autoload files containing 523 classes

Classmap and the optimised autoloader: the PSR-4 autoloader checks the disk for a file every time it loads a class. A classmap is a ready-made list of every class and its file. composer dump-autoload -o (or --optimize) converts all PSR-4 rules into a classmap, which is faster — the standard for production deploys (composer install --no-dev -o). --classmap-authoritative (-a) goes further: a class not in the map isn't searched for at all, which is fastest but means classes created at runtime can't be loaded. The classmap key in composer.json also loads old code that doesn't follow PSR-4: Composer scans the listed folders for classes.

files autoloading: functions can't be autoloaded, so a file of plain functions — like BookBay's src/helpers.php with BookBay\shopName() — goes under "files" in the autoload section. Those files are loaded on every request, as soon as vendor/autoload.php is included. Keep the list short and the files small; for anything bigger, a class with static methods (Act 11) can be autoloaded instead.

PSR-0, the history: before PSR-4 (2013), the standard was PSR-0 (2010). It mapped full namespaces to folders including the prefix, so BookBay\Booking\Booking lived in src/BookBay/Booking/Booking.php — one extra folder level for every package. It also turned underscores in class names into folders, because old pre-namespace code wrote "namespaces" as Zend_Http_Client (chapter 1). PSR-0 is deprecated; you'll only meet it in very old packages, and Composer still supports it under psr-0. The table below compares every autoloading option.

Table — Autoloading options in composer.json
KeyExampleHow it finds the fileUse for
psr-4"BookBay\\": "src/"Namespace prefix → folder, rest of the name → pathAll modern code
classmap["legacy/"]Scans folders once and lists every classOld code without namespaces
files["src/helpers.php"]Always loaded with vendor/autoload.phpPlain functions and constants
psr-0"BookBay\\": "src/"Full namespace → folder (src/BookBay/…), _ → /Very old packages only
autoload-dev"BookBay\\Tests\\": "tests/"Same keys, development onlyTests and dev tools

Key Takeaway

An autoloader, registered with spl_autoload_register(), is called with the fully qualified name the first time PHP meets an unknown class, interface, trait or enum, and requires its file — classes load lazily and functions never autoload. PSR-4 maps a namespace prefix to a folder ("BookBay\\": "src/" → BookBay\Booking\BookingStatus in src/Booking/BookingStatus.php). Composer generates the autoloader: one require of vendor/autoload.php per entry script loads your classes and every package's. File names must match class names letter for letter, or Linux servers can't find them. In production use dump-autoload -o (a classmap); put plain-function files under "files".

Why This Matters

Every modern PHP project, Laravel included, loads its classes this way: one vendor/autoload.php, PSR-4 folders, and no require for classes anywhere. Knowing the mapping tells you where to find any class in any project — and where to put a new one.

"Class not found" on the server but not on your laptop is a classic PHP production bug, and it's almost always a file name's capital letters. Now you know why, and how to catch it before deploying.

The fourteen require_once lines are gone: one require of vendor/autoload.php, and every class loads itself. But the project's README now has a long list of commands — run the reminders, check the code, clear the cache, each typed slightly differently by each person — and Marcus's PHPStan (Act 21) is a different version from Mia's. That's the next chapter: Composer scripts, binaries and configuration.