Home » Php » php – Dependency injection in MVC

php – Dependency injection in MVC

Posted by: admin July 12, 2020 Leave a comment

Questions:

I’m trying to create simple MVC skeleton and I’m stuck with 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

The question is: how can any object get access to any dependency?

Some examples:

  • Controller may need Config to get output formatting options.
  • Mapper may need Database to perform queries.
  • Any Controller / Helper needs access to Log.
  • Helper may need any number of dependencies (ex.:Uri_Helper needs Router).

The only possibility I can think of is to use Registry, but this violates Law of Demeter (ask what you really need).

How to&Answers:

You write factories(excellen article). This could be totally boring(like the article mentions) so you could use a DI-framework like for example:

  • Symfony DIC: See Juraj’s post.
  • PD
  • Yadif
  • Drip(PHP4): but hasn’t been updated in a while.

Also I would like to point out that Misko’s blog is very interesting and has a lot of good reads on how to do testing properly. Especially the guide to writing testable code is a must read.

P.S: I think you should be writing factories, because PHP is a scripting language and you should use as little code as possible to make your site fast. That’s the problem with some PHP frameworks.

Rasmus Ledorf(PHP inventor) ‘s quote:

Many frameworks may look very
appealing at first glance because they
seem to reduce web application
development to a couple of trivial
steps leading to some code generation
and often automatic schema detection,
but these same shortcuts are likely to
be your bottlenecks as well since they
achieve this simplicity by sacrifizing
flexibility and performance. Nothing
is going to build your application for
you, no matter what it promises. You
are going to have to build it
yourself. Instead of starting by
fixing the mistakes in some foreign
framework and refactoring all the
things that don’t apply to your
environment spend your time building a
lean and reusable pattern that fits
your requirements directly. In the end
I think you will find that your
homegrown small framework has saved
you time and aggravation and you end
up with a better product.

Answer:

You may use a dependency injection container like Symfony DIC. You define your objects, configuration and wiring inside the container, which than takes care of instantiation.