当注入构造函数时,我似乎无法让 PHP-DI 正确解析其配置类的接口。在下面的代码中,使用容器获取\Foo\IDog会返回一个Poodle类,但是当使用容器获取\Foo\Kennel(在构造函数中有一个\Foo\IDog)时,它不再识别它被配置为返回一个贵宾犬和错误说:
"Entry "\Foo\Kennel" cannot be resolved: Entry "Foo\IDog" cannot be resolved: the class is not instantiable"
这是概念证明:
<?php
namespace Foo;
require(__DIR__ . "/vendor/autoload.php");
interface IDog {
function bark();
}
class Poodle implements IDog {
public function bark() {
echo "woof!" . PHP_EOL;
}
}
class Kennel {
protected $dog;
public function __construct(\Foo\IDog $dog) {
$this->dog = $dog;
}
public function pokeDog() {
$this->dog->bark();
}
}
$containerBuilder = new \DI\ContainerBuilder();
$containerBuilder->addDefinitions([
"\Foo\IDog" => \DI\autowire("\Foo\Poodle")
]);
$container = $containerBuilder->build();
//Works:
$mydog = $container->get("\Foo\IDog");
$mydog->bark();
//Does not work:
$kennel = $container->get("\Foo\Kennel");
$kennel->pokeDog();
奇怪的是,如果我从中删除所有命名空间,它工作正常(这里没有命名空间:https ://gist.github.com/brentk/51f58fafeee8029d7e8b1e838eca3d5b )。
知道我做错了什么吗?