PHP › Namespaces & Autoloading

How does Composer's classmap and files autoloading mechanism differ from PSR-4, and when would you use these alternative approaches instead?

Advanced

Answer

Classmap autoloading builds a direct map of every specific class to its exact file location by scanning specified directories, which is useful for legacy code that does not follow a consistent namespace and directory structure convention like PSR-4 requires, while files autoloading simply ensures specific files, often containing global helper functions rather than classes, are always automatically included on every request, both providing flexibility for situations that do not neatly fit the PSR-4 convention.
{
  "autoload": {
    "classmap": ["legacy/"],
    "files": ["src/helpers.php"]
  }
}
Real-world example A project incorporating an older legacy codebase that does not follow PSR-4 conventions uses classmap autoloading specifically for that legacy directory, while still using standard PSR-4 for all of its newer, properly organized code.

Common follow-ups: What is the performance tradeoff between classmap and PSR-4 autoloading?;Why is using files autoloading for global helper functions sometimes considered less ideal than a proper class based approach?