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 avendor
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).