Dependency injection

The Dependency Injection is a complicated term that define a simple idea everybody is using with or without knowing it.

I will try in this post to share the essential and explain it as simple as possible.

What is Dependency Injection (DI)?

A DI is a popular design pattern for large scale Software. The purpose is to simplify the deployment and the Unit tests. However to do so you will need to create a more complex architecture! Before using this design pattern ask yourself if you need it. If your Software can be used on different platforms and configurations you probably need it, if not then it is up to you.

Exemple using PHP

Let’s say your Software is about boats and in order to create a boat Object you need to establish a Database connection.

You naturally create

Class Boat
{
	public function __construct()
	{
		$this->db = new Database('myHost', 'myDb', 'myUser', 'myPassword');
	}
}

As you can see in that example the Boat Class instantiate itself the Database instance with its own parameters. Boats Objects are dependant on the Database Class and its four hard-coded parameters. Without them the database connection is corrupted.

In the future let’s say that you have more Objects that use the same code across your platform. You have Boat, Car, Bus, Plane etc. with the same hard-coded dependency.

If you want to change the Database parameters you will need to go to all your files and change the dependency. This is really bad behaviour when it comes to fair large Software.

Class Boat
{
	public function __construct(String $host, String $db, String $user, String $pass)
	{
		$this->db = new Database($host, $db, $user, $pass);
	}
}

Now we added parameters to the constructor. The same four values are now provided by the piece of code that creates the Boat instance. If you want to change the Database parameters in the future you will not have to change Boat code.

Are we done? Well this is a bit better but our Boat Class is still depending on the Database Class and the four same values.

What happen if in the future you want to use another Database Class? Well once again you will need to change your code…We can do better than that!

Class Boat
{
	public function __construct(Object $db)
	{
		$this->db = $db;
	}
}

In this example our Boat Class is no longer dependent on the Database Class or the four previous values! The piece of code that creates a Boat Class has to inject the Database Object.

Sources

Leave a Reply

Your email address will not be published. Required fields are marked *