PSR-4 Autoloading

JA JASWANT Updated 04 Nov 2026
6 min read ·Lesson 230 of 238

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

  1. A fully qualified class name has the form 0NamespaceName>(1SubNamespaceNames>)*2ClassName> — there must be at least a top-level namespace (the "vendor" namespace).
  2. A contiguous series of leading namespace segments (the prefix, such as App0 or GoCourse\Shop`) maps to a base directory.
  3. The remaining namespace segments map to subdirectories; namespace separators become directory separators.
  4. The class name becomes the file name with the .php suffix.
  5. Names are case-sensitive where the filesystem is: App\Billing\Invoice must be in Billing/Invoice.php, not billing/invoice.php.
  6. 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

  1. 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.
  2. Prefixes are tried longest first, so the more specific App\Legacy0 mapping overrides the general App` mapping for legacy classes.
  3. The relative class name's backslashes become slashes, and .php is appended.
  4. 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 in src/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-dev mappings 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 in vendor/composer/autoload_psr4.php.

Other Autoloading Types in Composer

TypeUse
psr-4The standard for all new code
classmapScan directories and build a class-to-file map — for legacy code that does not follow PSR-4
filesFiles included on every request — for global functions (functions cannot be autoloaded)
psr-0An older, deprecated standard (underscores in class names mapped to directories); found only in very old libraries

Troubleshooting "Class Not Found"

CheckTypical 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.json and let Composer generate the loader.
  • Keep test classes in autoload-dev, and use classmap only for legacy code.
  • Regenerate optimized class maps during deployment. Official reference: https://www.php.net/manual/en/language.oop5.autoload.php

0 Comments

Reviewed before they appear

No comments yet.

PHP
PHP Home PHP Switch PHP Match Alternative Syntax PHP Loops While Loop Do While Loop For Loop Foreach Loop Nested Loops Break Statement PHP Intro PHP Install PHP Built-in Web Server PHP Syntax PHP Tags PHP and HTML PHP Comments PHP Multiline Comments PHP Variables Variables Scope PHP Casting Logical Operators Null Coalescing Operator Spaceship Operator Operator Precedence Continue Statement Modify Strings PHP If...Else...Elseif PHP If Modify Strings PHP If Operators PHP Functions Concatenate Strings PHP If...Else User-defined Functions Slicing Strings Function Arguments PHP Shorthand if Escape Characters Default Argument Values PHP Nested if Pass by Reference String Interpolation Named Arguments PHP File Upload Variadic Functions Return Values Search in Strings Multibyte Strings Type Declarations in Functions PHP Numbers PHP Math PHP Floats PHP Random Numbers PHP Constants PHP Properties PHP Methods PHP Constructor Constructor Property Promotion PHP Cookies PHP Destructor PHP Access Modifiers Readonly Properties PHP Sessions PHP Inheritance Method Overriding PHP Filters The final Keyword CSRF Protection PHP Filters Advanced Session Security Secure Cookies PHP Magic Constants File Upload Security PHP Callback Functions PHP Operators Filesystem Security PHP JSON Arithmetic Operators Error Reporting in Production Hiding PHP Assignment Operators PHP Configuration (php.ini) Comparison Operators PHP Command Line (CLI) PHP Exceptions Increment / Decrement Operators Migrating to PHP 8 PHP Form Validation PHP Form Required PHP Form URL/E-mail Error Handling Form Input Sanitizing Escaping Output (htmlspecialchars) Custom Error Handler Checkbox, Radio and Select Inputs Sticky Forms PHP Form Complete PHP Date and Time Date Formatting Error Logging HTTP Headers and Redirects Output Buffering Sending Email PHP cURL Consuming REST APIs PHP Generators AJAX PHP AJAX Database AJAX XML AJAX Live Search AJAX Poll AJAX with JSON Security Introduction Password Hashing SQL Injection Prevention XSS Prevention Garbage Collection Project: Simple Blog PHP What is OOP PHP Classes/Objects The $this Keyword Access Array Items Update Array Items Add Array Items Remove Array Items Sorting Arrays Multidimensional Arrays Array Destructuring Array Spread Operator Search in Arrays Merge Arrays PHP Abstract Classes PHP Interfaces Polymorphism PHP Traits PHP Static Methods PHP Static Properties Late Static Binding Magic Methods Object Cloning MySQL Database MySQL Connect MySQL Create DB MySQL Create Table MySQL Insert Data MySQL Get Last ID MySQL Insert Multiple MySQL Prepared MySQL Select Data MySQL Where Debugging PHP Project: Image Upload Gallery $_SESSION $_ENV PHP RegEx RegEx Patterns Heredoc and Nowdoc RegEx Modifiers preg_match preg_replace preg_split PHP RegEx Functions Nullable Types Mixed and Never Types Nullsafe Operator PHP Attributes PHP Fibers Readonly Classes Property Hooks (PHP 8.4) Asymmetric Visibility (PHP 8.4) Reflection API SPL Data Structures Composer PHP Form Handling PDO Transactions PDO Error Handling PHP XML Parsers PHP SimpleXML Parser PHP SimpleXML - Get PHP XML Expat Parser PHP DOM Parser PHP XMLReader PHP XMLWriter AJAX Intro PHP Class Constants Encryption with Sodium Recursive Functions Variable Functions Anonymous Functions Closures Arrow Functions First-class Callable Syntax PHP Arrays Indexed Arrays Associative Arrays Create Arrays Variables Scope Static Variables Variable Variables PHP Echo / Print PHP printf / sprintf PHP Data Types PHP Booleans PHP NULL PHP Strings String Functions array_map / array_filter / array_reduce Array Functions PHP Superglobals $GLOBALS What Is `$_SERVER` ? $_REQUEST $_POST $_GET $_FILES $_COOKIE PHP Type Juggling MySQL Order By MySQL Delete Data MySQL Update Data MySQL Limit Data MySQL Joins with PHP Pagination with PHP PDO Introduction PDO Connect PDO Prepared Statements PDO Fetch Modes PSR-4 Autoloading Installing Extensions (PECL / PIE) OPcache & Performance PHP-FPM Project: Contact Form with Email Project: Login & Registration System Project: CRUD App with MySQL Project: Shopping Cart with Sessions Project: REST API with PHP
Ask about this post
AI Ask about this post

Ask questions about PSR-4 Autoloading and get answers drawn from it.

Signed-in readers only.