autoLoad.php _baseDir = rtrim((string)$baseDir, DIRECTORY_SEPARATOR); } /** * 设置别名 * * @param $prefix 别名 * @param $path 真实路径 */ public function setAlias($prefix, $path) { if (!$prefix) { throw new \Exception('Error Alias
_baseDir = rtrim((string)$baseDir, DIRECTORY_SEPARATOR); } /** * 设置别名 * * @param $prefix 别名 * @param $path 真实路径 */ public function setAlias($prefix, $path) { if (!$prefix) { throw new \Exception('Error Alias', -__LINE__); } $length = strlen($prefix); if ('\\' !== $path{$length - 1}) { $prefix .= '\\'; ++$length; } $this->_alias[$prefix] = $path; $this->_aliasLength[$prefix{0}][$prefix] = strlen($prefix); } /** * 设置扩展名 * * @param $ext .php */ public function setExt($ext) { $this->_ext = (string)$ext; } /** * 注册 * * @param $prepend 如果是true,spl_autoload_register()会添加函数到队列之首,而不是队列尾部。 */ public function register($prepend = false) { spl_autoload_register([$this, 'load'], 0, $prepend); } /** * 自动加载函数 * * @param $class 命名空间 * @return bool */ public function load($class) { $classFormat = strtr($class, '\\', DIRECTORY_SEPARATOR); // 根据别名获取路径 $file = $this->getAliasFile($class); if ($file !== false) { require $file; return true; } // 无别名,拼接路径 $file = sprintf("%s%s%s%s", $this->_baseDir, DIRECTORY_SEPARATOR, $classFormat, $this->_ext); if (is_file($file)) { require $file; return true; } return false; } /** * 根据别名获取路径 * * @param $class 命名空间 * @return mixed string | bool */ private function getAliasFile($class) { $classFormat = strtr($class, '\\', DIRECTORY_SEPARATOR); $first = $class{0}; // 判断别名的首字母存不存在 if (!isset($this->_aliasLength[$first])) { return false; } // 判断别名,拼接路径 foreach ($this->_aliasLength[$first] as $prefix => $length) { if (0 !== strpos($class, $prefix)) { continue; } $dir = $this->_alias[$prefix] . DIRECTORY_SEPARATOR . substr($classFormat, $length); $file = sprintf("%s%s%s%s", $this->_baseDir, DIRECTORY_SEPARATOR, $dir, $this->_ext); if (!is_file($file)) { return $file; } } return false; } }