K
K
knowledge2018-02-26 18:57:09
PHP
knowledge, 2018-02-26 18:57:09

How is a competent transfer of the DI object to the constructor carried out?

I decided to try using dependency injection in my application, and then a problem arose
. I have a front controller, an index.php file, there I create an instance of a container (in particular, pimple) and pass
$di = new Pimple\Container():
$di to the launched application ['config'] = require_once __DIR__.'config.php':
$app = new Application($di):
$app->run():
And everything is great, injected.
Next, I have a controller class, with its own namespace. How do I inject in this case, create the di object again?
$di = new Pimple\Container():
new PostController($di):
In this case, the config file will be read again, more precisely, the require_once construction will not allow it to be read by returning one, and my goal is to use the configs as a singleton, which I actually implemented, but now I need to do it through dependency injection

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Artem Soshnikov, 2018-02-28
@artem90

Dock in a bunch of answers:
A container is created at the entry point of the application.
Further, the first and only place where there should be a call to the container is, for example:
Everything else is already injected into the desired controller.
The example, of course, is greatly exaggerated, but the point is that only 1 piece of code should know about the dependency container - the entry point.
The rest of the application should have no idea about the container, and should only receive dependencies.
Otherwise, the application will depend on a specific implementation of the DI container and, in general, on some container. A container is just a tool for managing dependencies, not a dependency)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question