Created
February 14, 2023 04:58
-
-
Save nazares/66e2bc4e59755114479d2da0de59daa4 to your computer and use it in GitHub Desktop.
php psr-4 autoloader
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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