我在使用 配置容器时设置了依赖项和定义ContainerBuilder
,然后编译它以获得实际的Container
.
我是否错过了injectOn()
方法的概念,或者我在这里做错了什么($this->translator
仍未分配)?我尝试了不同的方法,既实例化类并将对象添加到,ContainerBuilder
并将其作为\DI\object()
定义传递,两者都具有相同的结果。
<?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 \DI\ContainerBuilder();
$containerBuilder->addDefinitions([
Translator::class => \DI\object(),
]);
$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