PHP-DI:注入到构造函数中的接口无法正确解析
PHP-DI: Interface being injected into constructor won't resolve correctly
我似乎无法让 PHP-DI 在构造函数中注入时正确解析其配置的接口 class。在下面的代码中,使用容器获取 \Foo\IDog return 一只 Poodle class,但是当使用容器获取 \Foo\Kennel(其中有一个 \Foo\IDog构造函数,它不再识别它被配置为 return 贵宾犬和错误说:
"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)。
知道我做错了什么吗?
我认为这是因为您的 class 名称在您的配置中无效:"\Foo\IDog"
无效,"Foo\IDog"
有效。
在代码中 \Foo\IDog
也有效,但在字符串中只有 Foo\IDog
有效。
避免这种情况的安全方法是使用 \Foo\IDog::class
。这样 PHP 会告诉你 class 不存在。
我似乎无法让 PHP-DI 在构造函数中注入时正确解析其配置的接口 class。在下面的代码中,使用容器获取 \Foo\IDog return 一只 Poodle class,但是当使用容器获取 \Foo\Kennel(其中有一个 \Foo\IDog构造函数,它不再识别它被配置为 return 贵宾犬和错误说:
"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)。
知道我做错了什么吗?
我认为这是因为您的 class 名称在您的配置中无效:"\Foo\IDog"
无效,"Foo\IDog"
有效。
在代码中 \Foo\IDog
也有效,但在字符串中只有 Foo\IDog
有效。
避免这种情况的安全方法是使用 \Foo\IDog::class
。这样 PHP 会告诉你 class 不存在。