This content originally appeared on DEV Community and was authored by Doeke Norg
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;
}
}
});
How to use this autoloader
- Save this file as
autoload.php
for example, and fill out the correct values for$namespace_mapping
-
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
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',
];
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.
This content originally appeared on DEV Community and was authored by Doeke Norg
Doeke Norg | Sciencx (2021-09-03T19:27:36+00:00) A simple PSR-4 autoloader. Retrieved from https://www.scien.cx/2021/09/03/a-simple-psr-4-autoloader/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.