Dependency Injection in MVC

I am trying to create a simple MVC skeleton and I am stuck in dependencies.

This is what I have now:

$config = new Config(); $database = new Database($config); $uri = new Uri('article/5'); $request = new Request($uri); $response = new Response; $router = new Router; $dispatcher = new Dispatcher($request, $response, $router); $dispatcher->dispatch(); // Routing, instantiate controller, execute action, send response 

Question: how can any object access any dependency?

Some examples:

  • To obtain output formatting options, the controller may need Config.
  • Mapper queries may require a database.
  • Any controller / assistant needs access to the Log.
  • An assistant may require any number of dependencies (for example: Uri_Helper requires a router).

The only opportunity I can think of is to use the registry, but that violates the Demeter Law (ask what you really need).

+8
php dependency-injection model-view-controller
source share
2 answers

You write factories (excellent article). This can be absolutely boring (as mentioned in the article), so you can use the DI-framework, for example, for example:

  • Symfony DIC: see Juraj post.
  • PD
  • Yadif
  • Drip (PHP4): but not updated after a while.

I would also like to note that the Misko blog is very interesting and has a lot of good reviews on how to properly test. A guide to writing testable code is especially recommended.

PS: I think you should write factories because PHP is a scripting language and you should use as little code as possible to make your site fast. This is a problem with some PHP frameworks .

Rasmus Ledorf (inventor of PHP):

Many frameworks may look very appealing at a glance, because they seem to reduce the development web application to a few trivial steps, leading to some code generation and often automatic circuit detection, but these same shortcuts are likely to be your bottlenecks, so how do they achieve this simplicity by sacrificing flexibility and productivity. Nothing is going to create your application for you, no matter what it is promises. You will have to build it yourself. Instead of eliminating errors in some foreign structures and reorganizing all things that are not related to your environment, it spends your time creating an accurate and reusable drawing that suits your requirements directly. In the end, I think you will find that your homegrown small frame saved you time and aggravation, and you end up with a better product.

+5
source share

You can use a dependency injection container like Symfony DIC . You define your objects, configuration and wiring inside the container, which does not require instantiation.

+1
source share

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


All Articles