我在使用ContainerBuilder
配置容器时具有设置依赖关系和定义,然后对其进行编译以获取实际的Container
,但是每当我尝试注入依赖项时,它们总是倾向于忽略它们。
我是否错过了injectOn()
方法的概念,还是我在这里做错了什么($this->translator
仍然没有分配)?我尝试过不同的方法,既可以实例化类并将对象添加到ContainerBuilder
,并将其作为DIobject()
定义传递,均为相同的结果。
<?php
include "../vendor/autoload.php";
class Translator
{}
class TextHandle
{
protected $translator;
public function setTranslator (Translator $translator)
{
$this->translator = $translator;
}
public function test ()
{
var_dump($this->translator);
}
}
class TestCase
{
protected $translator;
public function __construct (Translator $translator)
{
$this->translator = $translator;
}
}
// Setup container
$containerBuilder = new DIContainerBuilder();
$containerBuilder->addDefinitions([
Translator::class => DIobject(),
]);
$container = $containerBuilder->build();
// Create object and inject
$textHandle = new TextHandle();
$container->injectOn($textHandle);
// Test injection, fails
$textHandle->test(); // NULL
// Test access, works
$translator = $container->get(Translator::class);
var_dump($translator); // object(Translator)#18 (0) {}
// Try having the container instantiate
$textHandle = $container->make(TextHandle::class);
$textHandle->test(); // Null
// Try object with constructor, works
$testCase = $container->make(TestCase::class);
var_dump($testCase); // Translator is set
根据文档,php-di不会通过setters进行自动化。
您应该添加TextHandle
类的定义,并通过设置器将其配置为Translator
:
$containerBuilder->addDefinitions([
TextHandle::class => DIobject()->method('setTranslator', DIget(Translator::class))
]);