编写器自动加载和命名空间的麻烦

时间:2015-12-29 11:06:17

标签: composer-php autoload

我试图创建一个Packagist / Composer包,用于一些训练,如果名称空间和作曲家。我无法弄清楚如何允许vendor/autoload.php进行自动加载。

可在此处查看实际代码:https://github.com/ThomasKasper/Passthrough或以下示例。

这是我的文件结构:

root
|---composer.json
|---src
    |----Passthrough
       |----Folder1
            |SomeClass.php
       |----Folder2
       |----Folder3
       |----Folder4

composer.json:

{
"name": "passthrough/passthrough",
"description": "A simple MVC framework",
"license": "MIT",
"keywords": ["passthrough", "framework"],
"require": {
    "php": ">=5.3.0"
},
"autoload": {
    "psr-4": {
        "Passthrough\\": "src/Passthrough"
    }
},
"autoload-dev": {
    "psr-4": {
        "Passthrough\\": "src/Passthrough"
    }
}
}

示例类:

<?php

namespace Passthrough\Folder1;

class SomeClass
{

}

App.php

require 'vendor/autoload.php';

use Passthrough\Folder1\SomeClass;

$route = new SomeClass();

var_dump($route);


Fatal error: Class 'Passthrough\Folder1\SomeClass' not found in C:\wamp\www\PassthroughTester\app.php on line 7

1 个答案:

答案 0 :(得分:0)

由于您的示例脚本没有失败,包括vendor/autoload.php,我们可以放心地假设您确实已经运行

$ composer dump-autoload

但是,如果您在运行上述命令后修改了自动加载配置,那么这可能就是无法找到该类的原因。

此外,假设已正确设置自动加载,则脚本失败的唯一原因可能是Passthrough\Folder1\SomeClass中的src/Passthrough/Folder1/SomeClass.php类不存在,自动加载器实际上正在寻找它

臆测

猜测,从您的示例脚本和到您的存储库的链接,该示例实际上可能如下所示:

require 'vendor/autoload.php';

use Passthrough\Routing\Route\Route;

$route = new Route('foo', function () {
    // . . . 
});

var_dump($route);

然后输出是这样的:

PHP Fatal error:  Class 'Passthrough\Base\Data\Callback' not found in /Users/am/Sites/stackoverflow/34509692/src/Passthrough/Routing/Route/Route.php on line 92
PHP Stack trace:
PHP   1. {main}() /Users/am/Sites/stackoverflow/34509692/app.php:0
PHP   2. Passthrough\Routing\Route\Route->__construct() /Users/am/Sites/stackoverflow/34509692/app.php:7

Fatal error: Class 'Passthrough\Base\Data\Callback' not found in /Users/am/Sites/stackoverflow/34509692/src/Passthrough/Routing/Route/Route.php on line 92

原因是Passthrough\Routing\Route\Route::__construct()中引用的课程Passthrough\Base\Data\Callback实际上并不存在于您的项目中。

相依

与您的问题无关,但为开发和非开发环境设置相同的自动加载没有意义,您应相应调整composer.json并删除autoload-dev部分:

{
    "name": "passthrough/passthrough",
    "description": "A simple MVC framework",
    "license": "MIT",
    "keywords": ["passthrough", "framework"],
    "require": {
        "php": ">=5.3.0"
    },
    "autoload": {
        "psr-4": {
            "Passthrough\\": "src/Passthrough"
        }
    }
}

供参考,请参阅https://getcomposer.org/doc/04-schema.md#autoload-dev