Answer the question
In order to leave comments, you need to log in
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
Answer the question
In order to leave comments, you need to log in
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 questionAsk a Question
731 491 924 answers to any question