4

我在使用 配置容器时设置了依赖项和定义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
4

1 回答 1

4

根据文档,PHP-DI 不通过设置器执行自动装配。

您应该添加类的定义并将其配置为通过 setterTextHandle注入:Translator

$containerBuilder->addDefinitions([
    TextHandle::class => \DI\object()->method('setTranslator', \DI\get(Translator::class))
]);
于 2016-11-25T15:16:15.493 回答