M
M
Miku Hatsune2015-12-19 19:43:14
PHP
Miku Hatsune, 2015-12-19 19:43:14

Is Dependency Injector Magic?

For a week I have been trying to understand how the dependency injector works "from the inside".
I dug php-di and seemed to understand ... php-di automatically injects the required class through the constructor and therefore it becomes much easier to replace the MyService class if needed later ...
Like this:

<?php
class MyService
{
    public function returnValue ()
    {
        return 'Hello World';
    }
}

class MyController
{
    private $myService;

    public function __construct (MyService $myService)
    {
        $this->myService = $myService;
    }

    public function action ()
    {
        echo $this->myService->getValue();
    }
}

$di = new DI\ContainerBuilder::buildDevContainer();

$myController = $di->get('MyController');
$myController->action(); // Выводит Hello World

For me, the code above is nothing more than magic, how did it know to pass exactly MyService?
And it’s still not clear, but what if you need, for example, 10 services in a class, register all of them manually in the constructor?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
K
Kirill Mokevnin, 2015-12-19
@Hatsune-Miku

Dependency injection can occur not only through the constructor, but also, for example, through setters. And many dependency injection libraries use reflection to find out "what is actually required". Reflection is the ability of programs to learn the structure of itself at runtime. In php, this is php.net/manual/ru/intro.reflection.php.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question