Composer Autoloading: PSR-4, Classmap, -o and --classmap-authoritative (and Why -a Breaks Drupal)

By Lars Nielsen ·

Composer has four autoloading strategies: PSR-4, classmap, files and the legacy PSR-0. In production you can turn PSR-4 into a classmap with composer dump-autoload -o, or make it authoritative with --classmap-authoritative (-a). This guide explains the lookup order in ClassLoader::findFile(), what each option changes (measured on a Drupal 11 site: 90 classmap entries become 6,713 with -o), and why -a breaks Drupal module classes.

Updated 15 November 2026: corrected the Drupal sections (Drupal registers module namespaces itself), the order of files includes, the advice to always re-dump after adding a class, and the scripts example. Added measurements from this site.

How the Composer Autoloader Works

Running composer install or composer dump-autoload generates vendor/autoload.php. Including that file registers a chain of autoloaders with PHP's spl_autoload_register(). When PHP encounters an unknown class name, it calls each registered autoloader in order until one resolves the file or all fail.

For each class, ClassLoader::findFile() in vendor/composer/ClassLoader.php does this, in order:

  1. Look the class up in the classmap. If it's there, done.
  2. If the classmap is authoritative, or the class already failed once in this request, stop: the class doesn't exist.
  3. If the APCu option is on, ask APCu.
  4. Try the PSR-4 prefixes, then PSR-0, then the fallback directories, checking each candidate path with file_exists().

files entries are not part of the lookup. They're included once, when vendor/autoload.php runs.

PSR-4: The Standard Approach

PSR-4 maps a namespace prefix to a directory. The rest of the fully qualified class name maps to a relative file path under that directory.

{
  "autoload": {
    "psr-4": {
      "Acme\\Blog\\": "src/",
      "Acme\\Admin\\": "admin/src/"
    }
  }
}

With this configuration:

ClassFile resolved to
Acme\Blog\Postsrc/Post.php
Acme\Blog\Repository\PostRepositorysrc/Repository/PostRepository.php
Acme\Admin\Dashboardadmin/src/Dashboard.php

The prefix must end with a backslash. Multiple prefixes can map to the same directory. The autoloader strips the prefix, converts the remaining namespace separators to directory separators, and appends .php.

PSR-4 in Drupal Modules

Drupal modules use PSR-4, but you don't register them in Composer. Drupal does it itself on every boot. DrupalKernel::getExtensionNamespacesPsr4() (in core/lib/Drupal/Core/DrupalKernel.php, Drupal 11.4) builds one mapping per enabled module and theme:

$namespaces["Drupal\\$extension"] = dirname($filename) . '/src';

It then adds them to Composer's own ClassLoader with addPsr4(). That's why Drupal\my_module\Controller\FooController in modules/custom/my_module/src/Controller/FooController.php loads without anything in composer.json.

This site's production composer.json has such a mapping anyway, for a custom module:

"autoload": {
  "psr-4": {
    "Drupal\\linkhub_performance\\": "web/modules/custom/linkhub_performance/src/"
  }
}

It's harmless, but redundant: Drupal registers the same prefix and directory as soon as the module is enabled. You do need a composer.json autoload entry for code outside a module, or for a module you publish as a package other projects use outside Drupal.

Multiple Roots for One Prefix

PSR-4 allows an array of directories for a single prefix. Composer checks each directory in order:

{
  "autoload": {
    "psr-4": {
      "Acme\\Blog\\": ["src/", "lib/"]
    }
  }
}

This is useful when splitting a namespace across a src directory and generated code.

Classmap: Maximum Performance

Classmap tells Composer to scan directories and build a complete class→file map at dump time. Every class lookup becomes a simple array access — no filesystem checks at runtime.

{
  "autoload": {
    "classmap": ["src/", "lib/", "something.php"]
  }
}

Composer generates a file like:

// vendor/composer/autoload_classmap.php
return [
    'Acme\\Blog\\Post'       => $baseDir . '/src/Post.php',
    'Acme\\Blog\\Tag'        => $baseDir . '/src/Tag.php',
    'LegacyLib_Util'         => $baseDir . '/lib/LegacyLib/Util.php',
];

Classmap is the right choice for:

  • Legacy code that doesn't follow PSR-0 or PSR-4 naming conventions
  • PEAR-style libraries (underscore-separated class names)
  • Any library where you want guaranteed resolution without prefix matching

Optimising PSR-4 with Classmap in Production

The most important production optimisation is --optimize-autoloader (or -o), which converts all PSR-4 and PSR-0 lookups into a classmap at dump time:

# During deployment
composer install --no-dev --optimize-autoloader --prefer-dist

# Or just regenerate the autoloader
composer dump-autoload --optimize --no-dev

For classes in the map, no file_exists() check is needed. Composer's documentation says of this level: "There are no real trade-offs with this method. It should always be enabled in production." You can also set it permanently with "optimize-autoloader": true under config in composer.json (Autoloader optimization).

What it does on this site, measured on a copy of the production code with Composer 2.11.2: the classmap as deployed has 90 entries (explicit classmap rules only). After composer dump-autoload -o --no-dev it has 6,713. I didn't measure the time difference, so there's no millisecond figure here. Composer's docs also point out that the map is cached by OPcache, so it loads almost instantly when OPcache is on.

Classes that Drupal registers at runtime aren't in that map: the optimized map has zero Drupal\node\ classes, because the node module's namespace isn't in any composer.json. Those are still found through PSR-4, which leads to the next section.

Authoritative Classmap

Go one step further with --classmap-authoritative (-a):

composer dump-autoload --classmap-authoritative --no-dev

This tells the autoloader: "if a class is not in the classmap, it doesn't exist — don't fall back to PSR-4 lookups." A missing class is then reported straight away instead of after a filesystem search. Do not use this during development: any new class file added without a dump-autoload is "not found".

Don't use it on a Drupal site at all. The authoritative check comes before PSR-4 (step 2 above), so the namespaces Drupal adds at runtime are never consulted. I tested this on a copy of this site's code. After registering the node module the way DrupalKernel does ($loader->addPsr4('Drupal\\node\\', 'web/core/modules/node/src')), $loader->findFile('Drupal\\node\\Entity\\Node') returns the file with the default autoloader and with -o, and false with -a. That test is at the class-loader level, not a full Drupal boot, but it's the same loader object Drupal uses. Composer's docs warn about the same mechanism for classes generated at runtime: they "will not be allowed to be autoloaded". If you want a cache for misses on such a site, the APCu option (--apcu) is the one that "cannot result in classes not being found".

Files: Guaranteed Inclusion at Bootstrap

The files strategy is not triggered by class name — it runs unconditionally every time vendor/autoload.php is included. Use it for global functions, constants, and polyfills that cannot be autoloaded.

{
  "autoload": {
    "files": [
      "src/helpers.php",
      "src/constants.php"
    ]
  }
}
<?php
// src/helpers.php — loaded on every request via Composer files autoload
if (!function_exists('array_value_recursive')) {
    function array_value_recursive(string $key, array $arr): array {
        $result = [];
        foreach ($arr as $k => $v) {
            if ($k === $key) {
                $result[] = $v;
            }
            if (is_array($v)) {
                $result = array_merge($result, array_value_recursive($key, $v));
            }
        }
        return $result;
    }
}

Common use cases:

  • Function libraries: ramsey/uuid 4.10 still ships src/functions.php this way
  • Symfony's String component, whose Resources/functions.php defines u(), b() and s()
  • Polyfills for older PHP versions (symfony/polyfill-*)
  • Application-wide constants defined outside a class

The order is defined: Composer includes them by dependency, so if package A depends on B, B's files come first. Packages with the same number of dependents are ordered alphabetically, and the root package's files always come last (schema docs). So you can't use files in your own project to override a dependency's function. Composer's advice is to include your file before vendor/autoload.php.

PSR-0: Legacy Support

PSR-0 has been deprecated by PHP-FIG since 21 October 2014, with PSR-4 recommended instead, but it's still encountered in old Drupal contrib, PEAR-era libraries, and Zend Framework 1. It differs from PSR-4 in one key way: underscores in class names are converted to directory separators.

{
  "autoload": {
    "psr-0": {
      "Twig_": "lib/"
    }
  }
}

The class Twig_Environment resolves to lib/Twig/Environment.php. Do not introduce new PSR-0 mappings. Migrate legacy code to PSR-4 when possible.

Autoloading in Development: dev Autoload

Test classes, fixtures, and tooling helpers belong in autoload-dev rather than autoload. They are excluded when dependencies install with --no-dev:

{
  "autoload": {
    "psr-4": {
      "Acme\\Blog\\": "src/"
    }
  },
  "autoload-dev": {
    "psr-4": {
      "Acme\\Blog\\Tests\\": "tests/"
    },
    "files": [
      "tests/bootstrap.php"
    ]
  }
}

Debugging Autoload Failures

Regenerate and Check

# Always regenerate after adding new classes or changing composer.json
composer dump-autoload

# Check where a class resolves
php -r "
\$loader = require 'vendor/autoload.php';
var_dump(\$loader->findFile('Acme\\\\Blog\\\\Post'));
"

Common Problems

SymptomLikely causeFix
Class not found after adding fileClassmap not regeneratedcomposer dump-autoload
Wrong class loaded (stale)Classmap authoritative with old cachecomposer dump-autoload -a
Drupal module class not foundModule not enabled, file not under src/ with the matching namespace, or an authoritative classmap (-a)Enable the module, check the path, dump without -a; a composer.json mapping isn't needed
Function "X" already definedFiles entry included by two packagesWrap functions in function_exists() guards
Slow bootstrap in productionPSR-4 filesystem scanning on every requestcomposer dump-autoload -o

Inspecting the Generated Autoloader

# See all registered PSR-4 namespaces
php -r "
\$loader = require 'vendor/autoload.php';
print_r(\$loader->getPrefixesPsr4());
"

# Count classmap entries
php -r "
\$map = require 'vendor/composer/autoload_classmap.php';
echo count(\$map) . ' classes in classmap\n';
"

Making it permanent in composer.json

Instead of remembering flags, set the optimization level once under config. For a Drupal site, Level 1 only:

{
  "config": {
    "optimize-autoloader": true
  }
}

For a non-Drupal application where nothing registers namespaces at runtime, you can use "classmap-authoritative": true instead. It implies optimize-autoloader (Composer docs).

Summary Checklist

  • Use PSR-4 for all new code; namespace prefix must end with a backslash, directory must exist
  • Use classmap for legacy libraries that don't follow PSR naming conventions
  • Use files only for global functions and constants — not for classes
  • Put test classes in autoload-dev so they're excluded from production installs
  • Run composer dump-autoload --optimize --no-dev during every production deployment
  • Consider --classmap-authoritative in production only if nothing registers namespaces at runtime. Never on Drupal, and never in development
  • After adding a class: with plain PSR-4 nothing is needed (the file is found by path); with a classmap rule or an optimized autoloader, run composer dump-autoload again
  • Debug resolution with $loader->findFile('Fully\\Qualified\\ClassName')
  • Drupal registers Drupal\<module>\ →<module>/src itself for every enabled module and theme. No composer.json entry needed

Related reading

Filed under

Leave a comment

Comments are reviewed before they appear.

Basic HTML allowed: links, emphasis, code and lists. Web addresses become links automatically.