How Composer Autoloading Works in PHP

Composer's autoloader maps namespaces to folders via PSR-4, so classes load automatically without manual require statements. Learn how it works and how to regenerate it.

Published September 18, 2026

Composer's autoloader lets you use any class in your project without a manual require or include statement, by mapping namespaces to directories as declared in composer.json.

"autoload": {
  "psr-4": {
    "App\\": "app/"
  }
}

Steps

  1. Declare a PSR-4 mapping in composer.json's autoload.psr-4 section, pairing a namespace prefix with a folder
  2. Require vendor/autoload.php once at your application's entry point
  3. Composer generates a class map that translates 'App\Models\User' into app/Models/User.php automatically when that class is first referenced

How it works

PSR-4 is a PHP-FIG standard specifying that a namespace segment corresponds directly to a directory segment, and the class name matches the file name. Composer reads this mapping and registers an autoload function via spl_autoload_register().

Things to watch for

  • After adding a new class or changing composer.json's autoload section, run 'composer dump-autoload' to regenerate the autoloader's internal class map
  • In production, run 'composer dump-autoload -o' (optimized) to generate a flat class map for faster lookups instead of PSR-4's directory-scanning fallback

FAQ

Why isn't my new class being found by Composer?

Run composer dump-autoload — Composer sometimes needs to regenerate its optimized class map after new files are added, especially if you're using the optimized (-o) autoloader.

More PHP articles