【问题标题】:How to use the PSR-4 autoload in my /Classes/ folder?如何在我的 /Classes/ 文件夹中使用 PSR-4 自动加载?
【发布时间】: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


【解决方案1】:

主要有两种方法可以让它工作:第一个选项是使用绝对服务器路径(以'/'开头),在你的自动加载函数中为你的类设置基本目录:

spl_autoload_register(function ($class) {

    $prefix = 'Classes\\';
    $base_dir = '/var/www/html/my_project/src/'; // your classes folder
    $len = strlen($prefix);
    if (strncmp($prefix, $class, $len) !== 0) {
        return;
    }
    $relative_class = substr($class, $len);
    $file = $base_dir . str_replace('\\', '/', $relative_class) . '.php';
    if (file_exists($file)) {
        require $file;
    }
});

更好的解决方案是,正如@Félix 建议的那样,坚持使用__DIR__ 常量以保持与您的项目文件夹相关的内容。不同服务器上的部署之间的绝对路径很脆弱。 __DIR__ 指的是使用它的文件所在目录;在这种情况下,它是您注册自动加载功能的地方。从此目录开始,您可以导航到类基目录,例如$base_dir = __DIR__ . '/../../src/;

别忘了给你的类命名:

namespace Classes;

class Foo
{
    public function test()
    {
       echo 'Hurray';
    }
 }

然后使用这样的类:

$foo = new Classes\Foo();
$foo->test();

【讨论】:

  • 啊,是的。我完全忘记了我的文件位于其他地方。但是我仍然无法在位于其他地方的文件中使用我的类。现在自动加载正在 index.php(项目的根目录)中完成。我可以在(例如)/etc/test.php 中很好地处理这些类。但是,当我在 /Frontend/templates/pages/test.php 中使用相同的类时,我收到一个错误,找不到类,我必须手动要求它。有什么解决办法吗?
  • 您确定使用了以反斜杠开头的绝对路径吗?这应该独立于调用脚本的文件夹。
猜你喜欢
  • 2018-04-10
  • 2023-03-09
  • 2015-01-08
  • 2015-04-20
  • 1970-01-01
  • 2014-07-25
  • 2014-10-19
  • 2014-07-18
  • 2023-01-31
相关资源
最近更新 更多