封裝自動載入邏輯,支援類別對應表查找與錯誤處理:
<?php
class ClassLoader {
private static $classMap = []; // 類別 -> 檔案路徑對應表
/**
* 註冊類別對應表
* @param array $map ['ClassName' => '/path/to/ClassName.php', ...]
*/
public static function registerMap(array $map) {
self::$classMap = $map;
}
/**
* 自動載入回調
*/
public static function autoload($class) {
if (empty($class)) {
throw new Exception("嘗試載入空類別名");
}
// 1. 查找對應表
if (isset(self::$classMap[$class])) {
$file = self::$classMap[$class];
if (file_exists($file)) {
require $file;
return;
}
throw new Exception("類別 $class 對應檔案不存在:$file");
}
// 2. 回退:PSR-4 風格自動解析
$file = __DIR__ . '/../src/' . str_replace('\\', '/', $class) . '.php';
if (file_exists($file)) {
require $file;
return;
}
throw new Exception("無法載入類別:$class");
}
/**
* 註冊/取消註冊自動載入器
*/
public static function register($enabled = true) {
if (!function_exists('spl_autoload_register')) {
throw new Exception('當前 PHP 環境不支援 spl_autoload_register');
}
if ($enabled) {
spl_autoload_register([__CLASS__, 'autoload'], true, true); // 拋出異常、優先執行
} else {
spl_autoload_unregister([__CLASS__, 'autoload']);
}
}
// 解構時自動取消註冊(可選)
public function __destruct() {
self::register(false);
}
}
// 使用範例
ClassLoader::registerMap([
'App\\Controller\\UserController' => '/var/www/app/Controller/UserController.php',
'App\\Model\\User' => '/var/www/app/Model/User.php',
]);
ClassLoader::register();
// 之後直接使用,無需 require
$user = new App\Model\User();
$ctrl = new App\Controller\UserController();
spl_autoload_register(
callable $autoload_function, // 載入回調
bool $throw = true, // true: 失敗拋出異常;false: 靜默失敗
bool $prepend = false // true: 插入隊列最前(優先執行)
);
vendor/autoload.phpopcache.enable=1 並預熱自動載入器,或使用 class_map_authoritative 快取對應表現代專案直接使用 Composer 管理自動載入:
// composer.json
{
"autoload": {
"psr-4": {
"App\\": "src/"
},
"classmap": ["legacy/"], // 不符合 PSR-4 的舊代碼
"files": ["helpers.php"] // 全域函數檔案
}
}
執行 composer dump-autoload -o 生成最優化的 vendor/autoload.php,專案入口僅需 require 'vendor/autoload.php'; 即可。