Get rid of autoload.php

Share this post on:

Inspired from simple-psr-4-autoloader .

Have you ever 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.

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.

<?php
spl_autoload_register(function (string $class_name): void {
    $namespace = 'MyProject';
    if (strpos($class_name, $namespace) === 0) {
        $class_file = './src';
        $class_file .=
            str_replace(
                [$namespace, '\\'],
                ['', DIRECTORY_SEPARATOR],
                $class_name)
                . '.php';
        if (file_exists($class_file)) {
            require_once $class_file;
            return;
        }
    }
});

Add this code to autoload.php and include it in index.php (or any other entrypoint you may have).

Share this post on:

Author: tayyebi

Tayyebi works in the role of Director at Gordarg where he is the founder. He is passionate about people, technology, and arts. Mohammad believes in communications, each of us has the power to empower their people with knowledge. He can be seen writing codes, playing music, biking, and reading.

View all posts by tayyebi >






www.Gordarg.com