Skip to content

Instantly share code, notes, and snippets.

@nazares
Created February 14, 2023 04:58
Show Gist options
  • Save nazares/66e2bc4e59755114479d2da0de59daa4 to your computer and use it in GitHub Desktop.
Save nazares/66e2bc4e59755114479d2da0de59daa4 to your computer and use it in GitHub Desktop.
php psr-4 autoloader
<?php
declare(strict_types=1);
$configuration = json_decode(file_get_contents(__DIR__ . '/../project.json'), true);
$namespaces = $configuration['autoload']['psr-4'];
function fqcnToPath(string $fqcn, string $prefix)
{
$relativeClass = ltrim($fqcn, $prefix);
return str_replace('\\', '/', $relativeClass) . '.php';
}
spl_autoload_register(function (string $class) use ($namespaces) {
$prefix = strtok($class, '\\') . '\\';
if (!array_key_exists($prefix, $namespaces)) {
return;
}
$baseDirectory = $namespaces[$prefix];
$path = fqcnToPath($class, $prefix);
require $baseDirectory . '/' . $path;
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment