LearnContact
Lesson 6620 min read

Autoloading

Learn how Composer's PSR-4 autoloading eliminates manual require statements and makes every installed or project class available on demand.

Introduction

Every example so far that used a library — like require 'vendor/autoload.php' before creating a new PHPMailer() — relied on autoloading. This lesson explains exactly how that single line makes every class in a project or its dependencies available without listing dozens of manual require statements.

You already learned namespaces earlier in this course. Autoloading is the piece that connects a namespace to an actual file on disk, automatically, the moment a class is used.

What You Will Learn
  • The problem autoloading solves as a project grows.
  • Composer's PSR-4 autoloading standard.
  • How to map a namespace to a folder in composer.json.
  • How to run composer dump-autoload.
  • How including vendor/autoload.php once makes every class available.

The Problem Autoloading Solves

Without autoloading, using a class defined in another file means manually requiring that file first — and every file that class depends on, and so on. In a small script this is manageable; in a real application with dozens or hundreds of classes, it quickly turns into an unmanageable wall of require statements that must be kept perfectly in sync with the codebase.

Without autoloading (tedious and fragile)
<?php
require 'classes/User.php';
require 'classes/Product.php';
require 'classes/Order.php';
require 'classes/Database.php';
require 'classes/Mailer.php';
// ...and one more line for every class the project ever adds

$user = new User();
The Goal

Autoloading lets you write new UserClass() anywhere in your code and have PHP automatically find and load the right file, with zero manual require statements for that class.

PSR-4 Autoloading

PSR-4 is a PHP community standard that defines a predictable way to map namespaces to folders. Under PSR-4, a namespace prefix corresponds to a base directory, and the rest of a fully qualified class name maps directly onto a file path inside it.

Fully Qualified Class NameMaps To File
App\\Models\\Usersrc/Models/User.php
App\\Services\\Mailersrc/Services/Mailer.php

Composer implements PSR-4 for you: once you tell it which namespace prefix maps to which folder, it generates an autoloader that resolves any class in that namespace to the right file automatically, without you writing a single require.

Configuring Autoload in composer.json

A project defines its own PSR-4 mapping inside the "autoload" section of composer.json. This tells Composer: "everything under the App\\ namespace lives inside the src/ folder."

composer.json
{
    "name": "programinds/demo-app",
    "require": {
        "phpmailer/phpmailer": "^6.9"
    },
    "autoload": {
        "psr-4": {
            "App\\": "src/"
        }
    }
}

With this mapping in place, a class file at src/Models/User.php should declare itself under the matching namespace.

src/Models/User.php
<?php

namespace App\Models;

class User
{
    public function __construct(public string $name)
    {
    }
}

Running composer dump-autoload

Whenever the autoload configuration in composer.json changes — or you add new classes that follow an existing mapping — Composer needs to regenerate its internal lookup tables. That is what composer dump-autoload does.

Regenerating the autoloader
composer dump-autoload
Example Output
Generating autoload files
Generated autoload files
When You Do (and Don't) Need This

Running composer require or composer install already regenerates the autoloader automatically. You typically only need composer dump-autoload manually after editing the "autoload" section of composer.json yourself, or after adding new classes that Composer has not indexed yet.

Including vendor/autoload.php

Composer generates a single file, vendor/autoload.php, which registers the autoloading logic for every dependency and for your own PSR-4-mapped classes. Including this one file, once, at the entry point of your application, is all that is needed for every class — yours and every installed package's — to become available on demand.

index.php (application entry point)
<?php

require __DIR__ . '/vendor/autoload.php';

use App\Models\User;
use PHPMailer\PHPMailer\PHPMailer;

$user = new User('Alex');
$mail = new PHPMailer();

echo 'Loaded user: ' . $user->name;
Output
Loaded user: Alex

Notice that neither User nor PHPMailer required an individual require statement. The moment PHP encounters new User(...), the autoloader steps in, works out the matching file from the namespace, and loads it automatically.

Autoloading and Namespaces

Autoloading only works because namespaces (covered earlier in this course) give every class a predictable, fully qualified name. PSR-4 is really just a formal agreement that a namespace segment corresponds to a folder segment, so tools like Composer can translate one into the other mechanically, without guessing.

Connecting the Dots

Namespaces solve naming collisions and organization. PSR-4 autoloading builds on top of that organization to answer one very practical question: "given this class name, which file is it in?" — and answers it automatically.

Common Mistakes

Avoid These Mistakes
  • Forgetting to include vendor/autoload.php at the entry point of the application.
  • Declaring a namespace in a class file that does not match its folder location under the PSR-4 mapping.
  • Editing composer.json's autoload section and forgetting to run composer dump-autoload afterward.
  • Mixing manual require statements with autoloading for the same classes, causing confusion or duplicate class errors.
  • Assuming autoloading works without a properly configured composer.json, even for your own project files.

Best Practices

  • Include vendor/autoload.php exactly once, at your application's single entry point.
  • Keep your namespace structure and folder structure perfectly aligned under PSR-4.
  • Run composer dump-autoload after changing the "autoload" mapping in composer.json.
  • Let Composer's autoloader handle both your own classes and third-party packages — avoid mixing in manual requires.
  • Use meaningful namespace prefixes (like App\\) that clearly separate your code from vendor code.

Frequently Asked Questions

Do I need to require every class file myself if I use Composer?

No. Once vendor/autoload.php is included and your PSR-4 mapping is set up in composer.json, PHP loads each class file automatically the first time that class is referenced.

What happens if my namespace does not match my folder structure?

The autoloader will fail to find the corresponding file and PHP will throw a "Class not found" error. The namespace segments must correspond exactly to the folder path configured under PSR-4.

Is PSR-4 the only autoloading style Composer supports?

Composer also supports older styles like classmap and files, but PSR-4 is the modern standard and the one almost all current libraries and applications use.

Why does composer require automatically update the autoloader?

Adding a package changes what needs to be autoloadable, so Composer regenerates vendor/autoload.php as part of that command, the same work composer dump-autoload does on its own.

Key Takeaways

  • Autoloading removes the need to manually require every class file in a growing project.
  • PSR-4 is the standard that maps a namespace prefix to a folder, letting tools resolve class names to files automatically.
  • The "autoload" section of composer.json defines this namespace-to-folder mapping.
  • composer dump-autoload regenerates the autoloader after mapping or structural changes.
  • Including vendor/autoload.php once, at the application's entry point, makes every mapped class available on demand.

Summary

Autoloading, powered by Composer and the PSR-4 standard, turns namespaces from an organizational convention into a fully automatic file-loading system. A single require of vendor/autoload.php replaces what would otherwise be dozens of manual require statements.

With dependency management and autoloading in place, you are ready to see how real applications organize their own code — starting with the next lesson's introduction to the MVC architectural pattern.

Lesson 66 Completed
  • You understand the problem autoloading solves as projects grow.
  • You can configure a PSR-4 mapping in composer.json.
  • You know when to run composer dump-autoload.
  • You can explain how including vendor/autoload.php once makes every class available.
Next Lesson →

MVC Architecture (Introduction)