Backend Development 3 min read

Understanding Composer Autoloading: PSR-0, PSR-4, Class‑Map, and Files

This article explains how Composer, the PHP dependency manager, supports four autoloading mechanisms—PSR‑0, PSR‑4, class‑map, and files—detailing their differences, configuration in composer.json, and practical code examples for loading classes.

php中文网 Courses
php中文网 Courses
php中文网 Courses
Understanding Composer Autoloading: PSR-0, PSR-4, Class‑Map, and Files

Composer is the PHP package dependency management tool, similar to npm for Node.js, and while not an official part of PHP it is widely used.

Composer provides four autoloading strategies for third‑party packages: PSR‑0, PSR‑4, class‑map, and files.

PSR‑0 Autoloading

PSR‑0 treats underscores in class names as directory separators.

PSR‑1 Basic Coding Standard

PSR‑2 Coding Style Guide

PSR‑3 Logging Interface

PSR‑4 Autoloading

PSR‑4 does not treat underscores specially; it maps namespaces directly to directory paths.

Example configuration in composer.json for PSR‑4:

<code>{
  "autoload":{
    "psr-4":{
      "FOO\\":"src/"
    }
  }
}</code>

When new FOO\A\A is instantiated in index.php , Composer looks for src/A/A.php and loads it if present.

PSR‑0

Example configuration in composer.json for PSR‑0:

<code>{
  "autoload":{
    "psr-0":{
      "FOO\\":"src/"
    }
  }
}</code>

With PSR‑0, the same class name leads Composer to search for src/FOO/A/A.php .

Class‑Map

Composer can scan specified directories for files ending in .php or .inc and generate a class‑map stored in vendor/composer/autoload_classmap.php :

<code>{
  "autoload":{
    "class-map":["a/","b/","c/"]
  }
}</code>

Files

The files autoload type allows manual inclusion of specific files, such as global function libraries:

<code>{
  "autoload":{
    "files":["src/my/function.php"]
  }
}</code>

These mechanisms give developers flexible ways to load classes and functions automatically when using Composer.

backendPHPComposerAutoloadingPSR-4
php中文网 Courses
Written by

php中文网 Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.