PHP-DI injectOn does not inject on setter methods

I have dependency and definition settings when setting up a container using ContainerBuilder, and then compiling it to get the actual one Container, but whenever I try to nest dependencies, they are always ignored.

Am I missing the concept of a method injectOn(), or am I doing something wrong here ( $this->translatorremains unassigned)? I tried different approaches to this, both creating an instance of the class, and adding an object to ContainerBuilder, and also passing it as a definition \DI\object(), as with the same result.

<?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
source share
1 answer

, PHP-DI .

TextHandle Translator :

$containerBuilder->addDefinitions([
    TextHandle::class => \DI\object()->method('setTranslator', \DI\get(Translator::class))
]);
+3

Source: https://habr.com/ru/post/1661951/


All Articles