What is dependency injection pattern, how to understand it?

Dependency Injection (DI) is a design pattern commonly used by many frameworks, and, is a good practice in development.

Understanding dependency injection is like a child game… really!

Let’s take an example with your phone battery. If you have an Iphone you probably have a phone integrated battery that you can’t remove, and, in many other smartphones, you have removable batteries.
All of these phones depend on a battery.

So, dependency injection is the fact of injecting any battery (dependency) in your phone without worrying about its name, its emplacement, its content. We also say that it helps reducing couplage.

Integrated batteries = no DI = high couplage.
Removable batteries = DI = low couplage.

Live example:

//No dependency injection, high code couplage
function phone (){
    $battery = new batterry();
    $battery->on();
}

//With dependency injection, low code couplage
function phone(Service $service){
    $battery = $service->get('battery');
    $battery->on();
}

Without dependency injection, your dependency is integrated inside your method, we say that the dependency and method are coupled. But, what if you need to change the battery class and what if you have dozens of methods like this? Surely you won’t want to update parts of your code everytime.

With dependency injection, you call a kind of service which is binded to a generic battery class. Everytime you’ll have to change the mother class, you’ll have to specify it in your service configuration without modifying your working code.

Edouard Kombo // @edouardkombo. Never stop learning.

Advertisements
What is dependency injection pattern, how to understand it?

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s