PSR-0 自动加载器问题

我在PSR-0自动加载的项目中按路径实例化类时遇到问题。结构如下:


| - src/

|    - Models/

|        - My_New_Model_Migration.php

|        - ...

|    SeederCommand.php

| - vendor/

|     - ...

| composer.json

和 Composer 自动加载器:


"autoload": {

    "psr-0": {

        "" : [

            "src/"

        ]

    }

}

不要在SeederCommand课堂上讲太多,它基本上是一个 Doctrine/migrations 类,它应该使用up()和down()方法创建迁移。


在负责生成这些的函数中,我有这部分:


if (file_exists(__DIR__ . "/Models/{$model}_Migration.php")) {

    $class = "{$model}_Migration";

    $instantiated = new $class;

    ....

}

当回显时,我注意到文件确实存在,所以这部分工作正常。但是,在更新课程时,我收到一个错误:


PHP 致命错误:未捕获的错误:在 /var/www/html/.../src/SeederCommand.php:97 中找不到类“/var/www/html/.../src/Models/My_New_Model_Migration.php”


由于路径是正确的,我认为问题一定是PSR-0自动加载器通过下划线解析路径来工作的?


有办法解决吗?


ibeautiful
浏览 156回答 2
2回答

Cats萌萌

类名中不能有下划线,目录结构中也不能有下划线。如果您的类名为Models_MyWhatever_Migration,因为您在迁移期间动态地将字符串“MyWhatever”添加到类名,则该类必须放置在src/Models/MyWhatever/Migration.php. 你不能把它放在src/Models/MyWhatever_Migration.php.如果您想保留下划线作为文件名的一部分,您必须切换到 PSR-4 并使用命名空间。

POPMUISE

创建新类的实例时出错$class = __DIR__ . "/Models/{$model}_Migration.php";$instantiated = new $class;这是错误的,因为您不能通过其文件名创建类的实例,例如:$instance = new /var/www/html/.../Class.php; // <-- wrong相反,您需要使用类名和命名空间:$instance = new \Project\Namespace\Class;所以在你的具体情况下,它可能是这样的$class = "\\Project\\Models\\".$model."_Migration";// ^ depends on the real namespace and name of your migration classes$instantiated = new $class;PSR-0 和下划线再次阅读PSR-0 标准后,老实说,我认为在使用 PSR-0 时无法实现您想要的(类名带有下划线但没有目录)。该标准明确指出:CLASS NAME 中的每个 _ 字符都转换为 DIRECTORY_SEPARATOR。可能的解决方案:Classmap 自动加载器但是您可以对这些文件使用作曲家的类映射自动加载器:该映射是通过扫描给定目录/文件中所有 .php 和 .inc 文件中的类来构建的。您可以使用类映射生成支持为所有不遵循 PSR-0/4 的库定义自动加载。要配置它,您可以指定所有目录或文件来搜索类。它可能看起来像这样(但我无法对其进行测试):"autoload": {&nbsp; &nbsp; "psr-0": {&nbsp; &nbsp; &nbsp; &nbsp; "" : [&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; "src/"&nbsp; &nbsp; &nbsp; &nbsp; ]&nbsp; &nbsp; },&nbsp; &nbsp; "classmap": ["src/Models/"]}
打开App,查看更多内容
随时随地看视频慕课网APP