DEV Community

Cover image for A simple PSR-4 autoloader
Doeke Norg
Doeke Norg

Posted on • Originally published at doeken.org

A simple PSR-4 autoloader

Have you even used a composer.json file purely for the need of registering a PSR-4 autoloader? I have, and it always felt a little weird to require such a hunk of code for such a simple task. It adds a vendor folder and a bunch of empty files. I don't like that overhead when it's not necessary.

So here is a drop-in alternative. You can for example use this in a WordPress theme or plugin.

spl_autoload_register(function (string $class_name): void {
    // Map the namespace to the corresponding folder
    $namespace_mapping = [
        'DoekeNorg\\BlogTheme' => 'src',
    ];

    foreach ($namespace_mapping as $namespace => $directory) {
        if (
            strpos($class_name, $namespace = trim($namespace, '\\')) !== 0
            || (!$directory = realpath(__DIR__ . DIRECTORY_SEPARATOR . trim($directory, DIRECTORY_SEPARATOR)))
        ) {
            continue; // Class name doesn't match or the directory doesn't exist
        }

        // Require the file
        $class_file = $directory . str_replace([$namespace, '\\'], ['', DIRECTORY_SEPARATOR], $class_name) . '.php';
        if (file_exists($class_file)) {
            require_once $class_file;
        }
    }
});
Enter fullscreen mode Exit fullscreen mode

How to use this autoloader

  1. Save this file as autoload.php for example, and fill out the correct values for $namespace_mapping
  2. require this file inside your bootstrap file or theme/plugin entry file

That's it. Now you can reference any class with that namespace, and the autoloader will require the correct file.

The mapping is relative to the location of the autoload.php file, so you can also do things like this:

|-- blog-theme
    |-- src
    |-- vendor
        |-- autoload.php <- the autoloader 
    |-- public
        |-- index.php <- entry file
Enter fullscreen mode Exit fullscreen mode

When you require vendor/autoload.php inside public/index.php you can adjust your mapping to the following,
and the resolving will still work.

 $namespace_mapping = [
    'DoekeNorg\\BlogTheme' => '../src',
];
Enter fullscreen mode Exit fullscreen mode

Couldn't you make this into a nice class?
Of course, but would that really be better?

Is it a big win over Composer?
No, a big win it is not, a small one; maybe. It's also not ment to replace Composer in any way, because that is way more optimized. It's just that for a simple plugin or theme you don't need the overhead Composer creates.

Top comments (0)