All articles

Build reusable PHP components

Autoload MyApp\Catalog\Product from src/ with SPL or Composer

Load a PHP class from src/ without requiring its file in the entry script. Compare an SPL callback with Composer PSR-4 and check the expected result.

Editorial illustration for Autoload MyApp\Catalog\Product from src/ with SPL or Composer

To load MyApp\Catalog\Product without a class-specific require in your entry script, register a callback with spl_autoload_register() or map the MyApp\ prefix to src/ in Composer. Both approaches point the requested class name at src/Catalog/Product.php. The SPL version makes that path calculation visible; the Composer version puts the mapping in composer.json and lets the entry script include vendor/autoload.php.

Start with the class and its path

Place this file at src/Catalog/Product.php, relative to the project root:

<?php

namespace MyApp\Catalog;

class Product
{
    public function label()
    {
        return 'Catalog product';
    }
}

For this mapping, MyApp\ identifies the base directory src/. The remaining Catalog segment identifies a subdirectory, and Product identifies Product.php. PSR-4 requires the subdirectory and filename to match the case of those class-name segments. src/catalog/Product.php and src/Catalog/product.php therefore do not meet the stated naming requirement. See the PSR-4 specification for the mapping rules.

Make the mapping explicit with SPL

Save this as entry-spl.php in the project root, alongside the src/ directory:

<?php

spl_autoload_register(function ($class) {
    $prefix = 'MyApp\\';
    $baseDirectory = __DIR__ . '/src/';

    if (strncmp($class, $prefix, strlen($prefix)) !== 0) {
        return;
    }

    $relativeClass = substr($class, strlen($prefix));
    $relativePath = str_replace('\\', '/', $relativeClass) . '.php';
    $file = $baseDirectory . $relativePath;

    if (is_file($file)) {
        require $file;
    }
});

$product = new \MyApp\Catalog\Product();
echo $product->label(), PHP_EOL;

When the entry script requests the class, its registered callback checks whether the name begins with MyApp\. If so, it removes that prefix and turns the remaining namespace separator into a directory separator. For this request, it calculates src/Catalog/Product.php beneath the entry script's directory. It includes the file only if that path exists. A name outside MyApp\ is left alone, rather than being interpreted as a file under src/.

That prefix check matters if an application registers more than one autoloader. PHP permits multiple calls to spl_autoload_register(); an exception from an autoload function interrupts the process and prevents later autoloaders from running. This callback simply returns when the name is outside its mapping. The PHP autoloading manual describes that behavior.

Give Composer the same mapping

For the Composer alternative, keep the same src/Catalog/Product.php. Put this configuration in composer.json at the project root:

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

After adding the mapping, run this from the project root:

composer dump-autoload

Composer generates vendor/autoload.php for application code to include. A separate entry-composer.php can then be:

<?php

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

$product = new \MyApp\Catalog\Product();
echo $product->label(), PHP_EOL;

This is an alternative entry script, not an instruction to register the SPL callback as well. With either setup and the files placed as shown, the requested class maps to the same source file. Neither entry script names Product.php in a require statement. The examples are intended to print:

Catalog product

That result would show that the Product declaration was available when the entry script created the object and called label(). If it does not appear, check the prefix, the src/ location and the case of both Catalog and Product.php against the requested name.

When Composer's lookup changes

Composer's default PSR-4 resolution checks the filesystem before it can conclusively resolve a class name. Its optional Level 1 optimization converts PSR-4 rules into a class map, so known classes can resolve to paths without that filesystem check. If that distinction matters for your project, Composer documents composer dump-autoload -o as one way to enable the optimization. It does not change the class name or the MyApp\ to src/ mapping in this example. See Composer's autoloader optimization documentation.

← All articles