Development

How to Set Up Composer Autoloading in a PHP Project

Composer autoloading lets PHP load a class when your code first references it. Define a namespace-to-directory mapping in composer.json, generate Composer's loader, and require vendor/autoload.php once at the application's entry point.

The useful result is a predictable relationship between a class name and a file. You can add another class without adding another require to every caller.

Set up Composer autoloading with PSR-4

This example needs PHP 8.1 or newer and Composer 2. Create a new directory containing this composer.json:

{
  "name": "example/autoload-demo",
  "require": {"php": ">=8.1"},
  "autoload": {
    "psr-4": {"Demo\\": "src/"}
  }
}

The trailing namespace separator matters. Demo\ is the namespace prefix; src/ is its corresponding directory. Composer describes that mapping in its autoload schema.

Create src/Greeting.php:

<?php

declare(strict_types=1);

namespace Demo;

final class Greeting
{
    /** Returns a greeting for the supplied name. */
    public function forName(string $name): string
    {
        return 'Hello, ' . $name . '!';
    }
}

Create hello.php in the project root:

<?php

declare(strict_types=1);

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

echo (new Demo\Greeting())->forName('Mike') . PHP_EOL;

Generate the loader and run the entry point:

composer install
php hello.php

The expected output is Hello, Mike!. No package dependency is necessary to use Composer's autoloader for your own application.

Follow the namespace through the directory tree

For Demo\Reports\MonthlyReport, the prefix consumes Demo\. The remaining Reports\MonthlyReport becomes Reports/MonthlyReport.php beneath src/. The file must declare namespace Demo\Reports; and the matching MonthlyReport class.

Match capitalization exactly. A class that appears to load on a case-insensitive development filesystem can fail after deployment to Linux. The PSR-4 specification defines the naming relationship.

use Demo\Greeting; only shortens a class name inside the current file. It does not install Composer, load vendor/autoload.php, or repair an incorrect namespace.

Know when to regenerate the loader

Regenerate after changing the mapping in composer.json:

composer dump-autoload
composer validate

With ordinary PSR-4 loading, a new correctly named class under an existing mapping can be discovered without changing the mapping. An authoritative classmap has different deployment requirements: newly added classes need a rebuilt map. Do not enable that optimization without understanding your release process. Composer documents these tradeoffs in its autoloader optimization guide.

Commit your application source and, for an application, the lockfile. Build the deployment artifact with its required vendor/ directory. A production host will not magically have the loader because it existed on your laptop.

Diagnose class-not-found errors in order

Check the entry point first. Does its __DIR__ resolve to the project root, and does vendor/autoload.php exist there? Then compare the complete class name, namespace prefix, directory, filename, and declared class.

Avoid solving a bad mapping by scattering manual includes through the application. That creates two loading systems and makes future failures harder to explain.

For a project that already has legacy files, migrate one namespace at a time. Keep the autoload change separate from behavior changes, following the approach in refactoring a PHP application without tests.

How do I check the setup before deployment?

Run composer install in a clean checkout, execute the entry point, and deliberately try a nested class. Test on a case-sensitive filesystem. The success criterion is that the artifact can load its own classes without relying on files outside the checkout.

For help untangling a legacy project's loading and dependency boundaries, discuss a focused PHP review.