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:

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

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:

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

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:

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

Files

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

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

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

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

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

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.