PSR-4 Autoloading
What Is PSR-4?
In simple terms: PSR-4 is an agreed-upon rule for where PHP class files live. If a class is called App\Billing\Invoice, PSR-4 says it is found in a predictable file such as src/Billing/Invoice.php. Because every project and library follows the same rule, one autoloader (usually Composer's) can find every class automatically. Technically: PSR-4 is a standard published by the PHP-FIG (PHP Framework Interop Group). It defines how a fully qualified class name maps to a file path: a namespace prefix corresponds to a base directory, the remaining namespace segments correspond to subdirectories, and the class name corresponds to a file name ending in .php. The basics of autoloading were introduced in Autoloading Classes; this lesson looks at the rules in detail, multiple mappings, a spec-compliant implementation, and troubleshooting.
The Mapping Rule
Fully qualified class name: App\Billing\Invoice
└┬─┘└───┬──────────┘
Namespace prefix: App\ → base directory: src/
Relative class name: Billing\Invoice
└──┬──┘ └──┬──┘
folder file
Resulting file: src/Billing/Invoice.php
The Rules in Detail
- A fully qualified class name has the form
0NamespaceName>(1SubNamespaceNames>)*2ClassName>— there must be at least a top-level namespace (the "vendor" namespace). - A contiguous series of leading namespace segments (the prefix, such as
App0 orGoCourse\Shop`) maps to a base directory. - The remaining namespace segments map to subdirectories; namespace separators become directory separators.
- The class name becomes the file name with the
.phpsuffix. - Names are case-sensitive where the filesystem is:
App\Billing\Invoicemust be inBilling/Invoice.php, notbilling/invoice.php. - Autoloaders must not throw exceptions or produce errors, and must not return a value — if they cannot find a class, they simply do nothing, so other autoloaders can try. The same rules apply to interfaces, traits, and enums.
Mapping Class Names to Paths
The core of a PSR-4 autoloader is a pure function from class name to file path:
<?php
function classToPath(string $class, array $prefixes): ?string
{
$class = ltrim($class, '\\');
// Longest prefixes first, so App\Legacy\ wins over App\
uksort($prefixes, fn(string $a, string $b): int => strlen($b) <=> strlen($a));
foreach ($prefixes as $prefix => $baseDir) {
if (str_starts_with($class, $prefix)) {
$relative = substr($class, strlen($prefix));
return rtrim($baseDir, '/') . '/' . str_replace('\\', '/', $relative) . '.php';
}
}
return null;
}
$prefixes = [
'App\\' => 'src/',
'App\\Legacy\\' => 'legacy/',
'Tests\\' => 'tests/',
];
$classes = [
'App\\Billing\\Invoice',
'App\\Legacy\\Report',
'Tests\\Billing\\InvoiceTest',
'\\App\\Support\\Money',
'Vendor\\Package\\Client',
];
foreach ($classes as $class) {
echo str_pad($class, 28) . '→ ' . (classToPath($class, $prefixes) ?? '(no mapping)') . "\n";
}
Output
App\Billing\Invoice → src/Billing/Invoice.php
App\Legacy\Report → legacy/Report.php
Tests\Billing\InvoiceTest → tests/Billing/InvoiceTest.php
\App\Support\Money → src/Support/Money.php
Vendor\Package\Client → (no mapping)
How It Works
- A leading backslash (as in
\App\Support\Money) is removed; PHP passes class names to autoloaders without it, but strings written by hand may include it. - Prefixes are tried longest first, so the more specific
App\Legacy0 mapping overrides the generalApp` mapping for legacy classes. - The relative class name's backslashes become slashes, and
.phpis appended. - Classes outside all prefixes return
null— the autoloader ignores them, and other registered autoloaders (for example, Composer's for vendor packages) can handle them.
A Spec-Compliant Autoloader Class
<?php
final class Psr4Autoloader
{
/** @var array<string, list<string>> */
private array $prefixes = [];
public function addNamespace(string $prefix, string $baseDir): void
{
$prefix = trim($prefix, '\\') . '\\';
$this->prefixes[$prefix][] = rtrim($baseDir, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR;
}
public function register(): void
{
spl_autoload_register($this->loadClass(...));
}
public function loadClass(string $class): void
{
$prefix = $class;
// Walk from the most specific namespace prefix to the least specific
while (($position = strrpos($prefix, '\\')) !== false) {
$prefix = substr($class, 0, $position + 1);
$relative = substr($class, $position + 1);
foreach ($this->prefixes[$prefix] ?? [] as $baseDir) {
$file = $baseDir . str_replace('\\', DIRECTORY_SEPARATOR, $relative) . '.php';
if (is_file($file)) {
require $file;
return;
}
}
$prefix = rtrim($prefix, '\\');
}
}
}
$loader = new Psr4Autoloader();
$loader->addNamespace('App', __DIR__ . '/src');
$loader->addNamespace('App', __DIR__ . '/lib'); // a second directory for the same prefix
$loader->register();
Key Features
- Multiple base directories per prefix:
App0 classes are searched insrc/first, thenlib/`. - Most specific prefix first: the loop starts with the full namespace and strips one segment at a time.
- Silent failure: if no file exists, the method returns without error, as the standard requires. In practice, Composer generates an optimized implementation of exactly this logic, so you configure it instead of writing it.
PSR-4 in Composer
{
"autoload": {
"psr-4": {
"App\\": "src/",
"App\\Legacy\\": "legacy/",
"Shared\\": ["lib/shared/", "modules/shared/"]
}
},
"autoload-dev": {
"psr-4": {
"Tests\\": "tests/"
}
}
}
- Prefixes end with
0(an escaped backslash in JSON). - A prefix can map to several directories (an array).
autoload-devmappings are only included when development dependencies are installed — test classes stay out of production builds.- After changing these settings, run
composer dump-autoload. The resulting mappings can be inspected invendor/composer/autoload_psr4.php.
Other Autoloading Types in Composer
| Type | Use |
|---|---|
psr-4 | The standard for all new code |
classmap | Scan directories and build a class-to-file map — for legacy code that does not follow PSR-4 |
files | Files included on every request — for global functions (functions cannot be autoloaded) |
psr-0 | An older, deprecated standard (underscores in class names mapped to directories); found only in very old libraries |
Troubleshooting "Class Not Found"
| Check | Typical Problem |
|---|---|
Does the namespace declaration match the directory? | File in src/Billing/ but declares namespace App\Billings; |
| Does the file name match the class name exactly, including case? | invoice.php vs Invoice — works on Windows/macOS, fails on Linux servers |
| Is there one class per file, named after the file? | Two classes in one file: only the one matching the file name is found |
Is the prefix configured in composer.json, with a trailing 0? | Missing or misspelled prefix |
Was composer dump-autoload run after changes? | Stale mappings |
| Is an authoritative class map in use? | With --classmap-authoritative, new classes are not found until the class map is regenerated |
Is the class in autoload-dev but the build used --no-dev? | Test helpers missing in production (often correct) |
Is vendor/autoload.php required in the entry point? | No autoloader registered |
Common Mistakes
Mismatched Namespace and Folder Names
Effect: The autoloader looks in the wrong place. Fix: Mirror namespaces exactly in the directory structure.
Case Differences
Effect: "Class not found" only on the Linux production server. Fix: Match capitalization exactly; run tests on Linux (for example, in CI).
Several Classes in One File
Effect: Some classes cannot be autoloaded. Fix: One class, interface, trait, or enum per file.
Throwing Exceptions in a Custom Autoloader
Effect: class_exists() checks and other autoloaders break. Fix: Return silently when a class is not found.
Best Practices
- Follow PSR-4: one class per file, namespaces mirroring directories, exact capitalization.
- Use a unique vendor/project namespace prefix (
App0,GoCourse\Shop`). - Configure autoloading in
composer.jsonand let Composer generate the loader. - Keep test classes in
autoload-dev, and useclassmaponly for legacy code. - Regenerate optimized class maps during deployment. Official reference: https://www.php.net/manual/en/language.oop5.autoload.php