0

我必须实现所有来源都像这样包含在内

$instance = new \d1\d2\d3\app\MyClass();

其中 d1\d2\d3\ 指向根目录。

我已经阅读了https://getcomposer.org/doc/04-schema.md#psr-4http://www.php-fig.org/psr/psr-4/上的基础知识 。https://laracasts.com/lessons/psr-4-autoloading上的示例也适用于我。

我的问题是:一旦我根据自己的需要稍微更改下面的代码,就找不到该类了。(是的,我在 composer.json 更改后发出命令composer update。是的,我使用自我更新更新了作曲家)。

所以这有效:

作曲家.json

"autoload": { "psr-4": {
"Laracasts\\": "app/Laracasts" } }

索引.php

require_once 'vendor/autoload.php'; // According to https://laracasts.com/lessons/psr-4-autoloading $test = new \Laracasts\Repositories\BlogRepository(); $test->hello();

但这不会:

作曲家.json

"autoload": { "psr-4": {
"d1\\": "app/Laracasts" } }

索引.php

require_once 'vendor/autoload.php'; // According to https://laracasts.com/lessons/psr-4-autoloading $test = new \d1\Repositories\BlogRepository(); $test->hello();

我究竟做错了什么?

我正在使用带有 IIS 8 的 php 5.3.28。

4

1 回答 1

0

解决了!

问题是 composer.json 中使用的前缀(在本例中为“d1”)也必须用作要包含的类中的命名空间前缀。当我发布上一篇文章时,情况并非如此。

对于上面的非工作示例,在“d1”的情况下文件必须如下所示:

应用程序\Laracasts\Repositories\BlogRepository.php

namespace d1\Repositories; class BlogRepository { public function hello(){ echo 'hello from a non-root dir!'; } }

索引.php

require_once 'vendor/autoload.php'; $test = new \d1\Repositories\BlogRepository(); $test->hello();

作曲家.json

{ "autoload": { "psr-4": { "d1\\": "app/Laracasts" } } }

d1\d2\d3\指向根目录的实现,我们要调整上面提到的所有3个文件中的前缀,将带有类的文件移动到根目录。然后我们像这样调整composer.json "d1\\d2\\d3\\": ""

于 2015-04-28T08:41:55.177 回答