Skip to content
Tutorials Center
My learning

Topics

Lesson 58 of 147 ยท Object-Oriented PHP

Autoloading and Composer

Learn how PHP autoloading works with spl_autoload_register and PSR-4, then use Composer - composer.json, require, autoload, versions, the lock file and Packagist.

A small script fits in one file. A real application has hundreds of classes, one per file, spread across folders, plus thousands more from libraries. Writing require 'src/Billing/Invoice.php'; for every class you use would be miserable and fragile: forget one and the page crashes, include one too many and you waste time loading code you don't need.

Autoloading fixes this. You register a function that PHP calls whenever code uses a class that isn't defined yet. The function turns the class name into a file path and loads it, just in time. Combined with the namespace-to-folder convention called PSR-4, a ten-line autoloader can load every class in a project. Composer, PHP's package manager, generates that autoloader for you and also downloads and updates the libraries your project depends on.

This lesson first builds a real PSR-4 autoloader you can run in the editor, then walks through Composer: composer.json, installing packages, version constraints, the lock file and Packagist. Our editor has no network and no Composer, so the Composer parts are shown as read-only commands and files that you'd run on your own machine.

Before autoloading: require everywhere

Without autoloading, every file has to include the files it needs:

PHP
<?php
require_once __DIR__ . '/src/Billing/Money.php';
require_once __DIR__ . '/src/Billing/Invoice.php';
require_once __DIR__ . '/src/Billing/InvoiceRepository.php';
require_once __DIR__ . '/src/Mail/Mailer.php';
// ...and so on, in every entry point

require_once loads a file once and skips it if it was already loaded. It still has problems: the list must be kept in sync by hand, order matters when one class extends another, and every request loads every listed file whether it's used or not. Old PHP projects often had a giant includes.php file like this.

spl_autoload_register

spl_autoload_register() registers a callable as an autoloader. When PHP needs a class, interface, trait or enum that doesn't exist yet, it calls each registered autoloader in order, passing the fully qualified class name. The autoloader's job is to define that class, usually by including a file. If no autoloader defines it, PHP throws the usual Class "..." not found error.

PHP Watching the autoloader get called

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The output shows the autoloader is called lazily: once for App\Greeter, the first time it's needed, and never again for that class. class_exists() also triggers autoloading unless you pass false as its second argument. (This demo uses eval() only to stand in for loading a file; never use eval() in real code.)

Other things worth knowing:

  • You can register several autoloaders. PHP tries them in order until one defines the class. Each library can register its own without conflicts.
  • An autoloader should do nothing for classes it doesn't handle, so the next autoloader gets a chance. It shouldn't throw.
  • Autoloading only works for classes, interfaces, traits and enums. Functions and constants are not autoloaded, so libraries load their function files explicitly (Composer has a files setting for that, shown later).
  • The old __autoload() function was removed in PHP 8.0. Always use spl_autoload_register().

PSR-4: from class name to file path

PSR-4 is the community standard that makes autoloading predictable. It says:

  1. A namespace prefix maps to a base directory, for example App\ โ†’ src/.
  2. The rest of the fully qualified class name, after the prefix, becomes a path below that directory, with \ replaced by /.
  3. The file name is the class name plus .php, with the exact same case.
TEXT
Prefix App\ โ†’ src/

App\Billing\Invoice            โ†’ src/Billing/Invoice.php
App\Billing\Tax\VatCalculator  โ†’ src/Billing/Tax/VatCalculator.php
App\Kernel                     โ†’ src/Kernel.php

Here's a complete PSR-4 autoloader, the same logic Composer uses. The example writes three class files into a temporary folder first, so you can watch real files being found and loaded:

PHP A working PSR-4 autoloader

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Each file is loaded exactly when its class is first used: Invoice.php at new Invoice(), Money.php at the first new Money(), and Clock.php only when Clock::today() runs. If the code never touched Clock, its file would never be read.

PSR-4 file names are case-sensitive on Linux servers. A class App\Billing\Invoice in a file named invoice.php loads fine on Windows and macOS (whose file systems are usually case-insensitive) and then fails in production. Keep the file name identical to the class name.

Composer

Composer is the standard dependency manager for PHP. It does two jobs:

  1. Dependency management: it downloads the libraries your project needs (and the libraries they need), at versions that are compatible with each other, into a vendor/ folder.
  2. Autoloading: it generates vendor/autoload.php, an optimized autoloader for your own classes and every installed package.

Composer is a PHP program itself (composer.phar), usually installed globally so you can run composer in any folder. Packages come from Packagist (packagist.org), the public registry with hundreds of thousands of packages.

Starting a project

Terminal
composer init                     # answer a few questions, creates composer.json
composer require monolog/monolog  # add a package (latest compatible version)
composer require --dev pestphp/pest   # a development-only package

composer require updates composer.json, resolves versions, downloads the code into vendor/, writes composer.lock and regenerates the autoloader, all in one step. A minimal composer.json for an application looks like this:

JSON
{
    "name": "acme/invoicing",
    "description": "Invoice management for Acme Ltd.",
    "type": "project",
    "require": {
        "php": "^8.4",
        "monolog/monolog": "^3.9"
    },
    "require-dev": {
        "pestphp/pest": "^4.0"
    },
    "autoload": {
        "psr-4": {
            "App\\": "src/"
        },
        "files": [
            "src/helpers.php"
        ]
    },
    "autoload-dev": {
        "psr-4": {
            "Tests\\": "tests/"
        }
    }
}

The important sections:

  • require: packages the application needs to run, plus the PHP version (and extensions like "ext-mbstring": "*") it requires.
  • require-dev: packages needed only for development: test frameworks, static analysis, debugging tools. Production deploys skip them with composer install --no-dev.
  • autoload: how to load your code. psr-4 maps namespace prefixes to folders exactly like the autoloader you just built. In JSON, backslashes are escaped, so "App\\" means App\. files lists files to include on every request, typically helper functions (which, remember, can't be autoloaded).
  • autoload-dev: autoloading for tests and other development-only code.

After changing the autoload section by hand, run composer dump-autoload to regenerate the autoloader.

Using the autoloader

Every entry point of your application (a web index.php, a CLI script, the test bootstrap) includes Composer's autoloader once, at the very top. After that, every class from your code and every package is available:

PHP
<?php
declare(strict_types=1);

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

use App\Billing\Invoice;
use Monolog\Logger;
use Monolog\Handler\StreamHandler;

$log = new Logger('billing');
$log->pushHandler(new StreamHandler(__DIR__ . '/logs/app.log'));

$invoice = new Invoice();
$log->info('Invoice created');

That single require is usually the only one in a modern PHP project.

Version constraints and semantic versioning

Packages follow semantic versioning (SemVer): versions look like MAJOR.MINOR.PATCH, for example 3.9.2.

  • PATCH (3.9.2): bug fixes only.
  • MINOR (3.9.0): new features, backward compatible.
  • MAJOR (3.0.0): breaking changes.

The constraint in composer.json says which versions you accept:

Constraint Accepts Typical use
^3.9 >=3.9.0 <4.0.0 the default: features and fixes, no breaking changes
^0.4 >=0.4.0 <0.5.0 before 1.0, minor versions may break
~3.9.1 >=3.9.1 <3.10.0 bug fixes only
3.9.2 exactly that version rarely; prevents even security fixes
>=3.0 <3.5 a custom range working around a known bad release
* anything avoid

The caret ^ is what composer require writes by default, and it's almost always what you want.

You can try the caret rule in PHP itself. The built-in version_compare() function compares version strings the same way Composer's constraints do for normal releases:

PHP Checking versions against a caret constraint

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Notice that 3.10.1 is newer than 3.9.2: version parts are compared as numbers, not as text. Composer picks the highest version that satisfies every constraint from your project and from all your packages, and reports a conflict if none exists.

composer.lock: install versus update

The first composer require or composer update writes composer.lock, which records the exact version (and commit hash) of every installed package, including indirect ones. Then there are two commands that are easy to mix up:

  • composer install reads the lock file and installs exactly those versions. Use it on teammates' machines, in CI, and on production servers. Everyone gets identical code.
  • composer update ignores the lock file, finds the newest versions allowed by composer.json, installs them and rewrites the lock file. Run it deliberately, test, then commit the new lock file.
Terminal
composer install                 # reproduce the locked versions
composer update                  # upgrade everything within the constraints
composer update monolog/monolog  # upgrade one package
composer outdated                # list packages with newer versions
composer audit                   # check installed packages for known vulnerabilities

Commit composer.json and composer.lock for applications. Never commit vendor/: add it to .gitignore, and run composer install after cloning. (Libraries usually don't commit their lock file, since the application that uses them decides the final versions.)

Production autoloading

In development, Composer's PSR-4 autoloader checks the file system to find each class. For production, generate a classmap, a precomputed array of every class and its file, which avoids those checks:

Terminal
composer install --no-dev --optimize-autoloader --classmap-authoritative

--classmap-authoritative also tells the autoloader not to look on disk for classes missing from the map. You can see the classmap idea in miniature: it's just an array lookup instead of a string-to-path calculation.

PHP A classmap autoloader

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Finding and choosing packages

Before adding a dependency, check it on Packagist and its repository:

  • Is it maintained: recent releases, issues answered, support for current PHP versions?
  • Is it popular and trusted (downloads, stars, used by known projects)?
  • Does it have a license compatible with your project (MIT, BSD and Apache are common)?
  • How many dependencies does it pull in? Every package is code you're trusting with your server.

Run composer audit regularly (and in CI) to be warned about packages with published security advisories. Keeping dependencies up to date is part of secure coding.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. When does PHP call a function registered with spl_autoload_register()?

    Autoloaders run lazily, the first time an undefined class-like name is needed. Functions and constants are never autoloaded.
  2. 2. With the PSR-4 mapping App\ to src/, which file holds App\Http\Controllers\HomeController?

    The prefix App\ is replaced by src/, the remaining namespace parts become folders, and the file name matches the class name exactly, including case.
  3. 3. Which constraint accepts version 3.12.0 but not 4.0.0?

    ^3.9 allows anything from 3.9.0 up to, but not including, 4.0.0. ~3.9.1 stops before 3.10.0.
  4. 4. What should a production deploy run?

    composer install reproduces the locked, tested versions. composer update can pull in untested newer versions and belongs in development.
  5. 5. Your autoloader receives a class name from another vendor's namespace. What should it do?

    Several autoloaders can be registered. Each one should only handle its own prefixes and stay silent otherwise.

Summary

  • Autoloading loads class files on demand. Register autoloaders with spl_autoload_register(); they receive the fully qualified class name and should ignore names they don't handle.
  • Only classes, interfaces, traits and enums are autoloaded, never functions or constants.
  • PSR-4 maps a namespace prefix to a base folder, the rest of the namespace to subfolders, and the class name to a file name with identical case.
  • Composer manages dependencies from Packagist and generates vendor/autoload.php. Configure your own code under autoload โ†’ psr-4 in composer.json.
  • Constraints follow semantic versioning; ^3.9 (any 3.x from 3.9) is the usual choice.
  • composer.lock pins exact versions: composer install reproduces them, composer update changes them. Commit the lock file, never vendor/.
  • In production, use composer install --no-dev --optimize-autoloader and run composer audit regularly.

Next: Comparing, Copying and Serializing Objects