当注入到构造函数中时,我似乎无法让PHP-DI正确地将接口解析为其已配置的类。在下面的代码中,使用容器get \Foo\IDog返回一个Poodle类,但是当使用容器get \Foo\Kennel (在构造函数中有一个\Foo\IDog )时,它不再识别它被配置为返回Poodle,并返回错误消息:
"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)。
知道我做错了什么吗?
发布于 2018-08-22 15:24:14
我认为这是因为你的类名在你的配置中无效:"\Foo\IDog"是无效的,"Foo\IDog"是有效的。
在代码中,\Foo\IDog也可以工作,但是在字符串中,只有Foo\IDog是有效的。
避免这种情况的安全方法是使用\Foo\IDog::class。这样PHP就会告诉你这个类不存在。
https://stackoverflow.com/questions/51957708
复制相似问题