【发布时间】:2018-02-20 01:51:30
【问题描述】:
我尝试了多个 PSR-4 加载器,但它们要么不起作用,要么我无法从另一个文件夹访问这些类。
我当前的文件夹结构:
-类
--Config.php
--Session.php
--前端(文件夹)
---登录.php
PSR-4 自动加载器:
我尝试使用 PSR-4 自动加载寄存器加载所有类。我稍微修改了我的文件夹结构。我已经给所有类命名空间 Classes,但 Frotend 文件夹中的类具有命名空间 Classes\Frontend。
spl_autoload_register(function ($class) {
// project-specific namespace prefix
$prefix = 'Classes\\';
// base directory for the namespace prefix
$base_dir = __DIR__ . '/Classes/';
// does the class use the namespace prefix?
$len = strlen($prefix);
if (strncmp($prefix, $class, $len) !== 0) {
// no, move to the next registered autoloader
return;
}
// get the relative class name
$relative_class = substr($class, $len);
// replace the namespace prefix with the base directory, replace namespace
// separators with directory separators in the relative class name, append
// with .php
$file = $base_dir . str_replace('\\', '/', $relative_class) . '.php';
// if the file exists, require it
if (file_exists($file)) {
require $file;
}
});
我不确定这是否与自动加载器有关,但我也想从任何文件中调用该类,无论它位于何处。所以如果我有一个文件
/Frontend/templates/login-page.php
我希望能够调用类“Classes\Frontend\Login”。
这可能吗?我该怎么做?
【问题讨论】:
-
你有composer吗?
-
请使用
composer! -
我正在创建某种库,应该很容易在其他项目中实现。使用作曲家不是一种选择。我一直在将 composer 用于一个独立的项目,这就是为什么我不知道如何在没有 composer 的情况下正确地做到这一点
-
如果您正在创建一个库并且不使用
composer,那么您将是唯一使用该库的人。
标签: php oop autoloader psr-4