feat: initial foundation for collaborative canteen ordering system in vanilla PHP
This commit is contained in:
@@ -0,0 +1,55 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Core;
|
||||
|
||||
class Autoloader
|
||||
{
|
||||
/**
|
||||
* Map of namespace prefix to base directory
|
||||
* @var array<string, string>
|
||||
*/
|
||||
private static array $prefixes = [];
|
||||
|
||||
/**
|
||||
* Register autoloader with SPL
|
||||
*/
|
||||
public static function register(): void
|
||||
{
|
||||
spl_autoload_register([self::class, 'loadClass']);
|
||||
}
|
||||
|
||||
/**
|
||||
* Add a base directory for a namespace prefix
|
||||
*/
|
||||
public static function addNamespace(string $prefix, string $baseDir): void
|
||||
{
|
||||
$prefix = trim($prefix, '\\') . '\\';
|
||||
$baseDir = rtrim($baseDir, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR;
|
||||
self::$prefixes[$prefix] = $baseDir;
|
||||
}
|
||||
|
||||
/**
|
||||
* Loads the class file for a given class name.
|
||||
*/
|
||||
public static function loadClass(string $class): bool
|
||||
{
|
||||
foreach (self::$prefixes as $prefix => $baseDir) {
|
||||
$len = strlen($prefix);
|
||||
if (strncmp($prefix, $class, $len) !== 0) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$relativeClass = substr($class, $len);
|
||||
$file = $baseDir . str_replace('\\', DIRECTORY_SEPARATOR, $relativeClass) . '.php';
|
||||
|
||||
if (file_exists($file)) {
|
||||
require_once $file;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user