Understanding Dependency Injection And Containers

Published Jul 06, 2017

Dependency injection and dependency injection containers are different things:

  • dependency injection is a method for writing better code
  • a container is a tool to help injecting dependencies

You don't need a container to do dependency injection. However a container can help you.

Classic PHP code

Here is how a code not using DI will roughly work:

  • Application needs Foo (e.g. a controller), so:
  • Application creates Foo
  • Application calls Foo
    • Foo needs Bar (e.g. a service), so:
    • Foo creates Bar
    • Foo calls Bar
      • Bar needs Bim (a service, a repository, …), so:
      • Bar creates Bim
      • Bar does something

Using dependency injection

Here is how a code using DI will roughly work:

  • Application needs Foo, which needs Bar, which needs Bim, so:
  • Application creates Bim
  • Application creates Bar and gives it Bim
  • Application creates Foo and gives it Bar
  • Application calls Foo
    • Foo calls Bar
      • Bar does something

This is the pattern of Inversion of Control. The control of the dependencies is inverted from one being called to the one calling.

The main advantage: the one at the top of the caller chain is always you. You can control all dependencies and have complete control over how your application works. You can replace a dependency by another (one you made for example).

For example what if Library X uses Logger Y and you want to make it use your logger Z? With dependency injection, you don't have to change the code of Library X.

Using a container

Now how does a code using a container works:

  • Application needs Foo so:
  • Application gets Foo from the Container, so:
    • Container creates Bim
    • Container creates Bar and gives it Bim
    • Container creates Foo and gives it Bar
  • Application calls Foo
    • Foo calls Bar
      • Bar does something

In short, the container takes away all the work of creating and injecting dependencies.

Discover and read more posts from Matthieu Napoli
get started