Dependency Injection(DI)
Dependency injection is a design pattern that use the Inversion of control principle(IoC)
What is Inversion of control ?
Inversion of Control (IoC) is a design principle. it is used to invert controls in object-oriented design to achieve loose coupling( called elements, depend on each other to the least extent practicable). controls refer to additional responsibilities a class has, other than its main responsibility.
before the type code to explain that let’s think a example of real life.
you are drive a car, you decide when to accelerate,brake,turn etc. you have a control of the car. for another side we have smarter cars they can take control, they know when accelerate, turn etc. you don’t have a control in this scene, this is IoC.
see this in code.
in the above code, the class example_two call the method test() from the class example, the class example_two can’t complete its task without the class example, its mean The Class example_two depend on Class Example. you can say The Class example is a dependency of Class example_two.
The IoC principle suggests to invert the control. This means to delegate the control to another class. In other words, invert the dependency creation control from class example_two to another class, as shown below.
As you can see above, class example_two uses Factory class to get an object of class example. Thus, we have inverted the dependent object creation from class example_two to Factory. Class Example_two no longer creates an object of class example, instead it uses the factory class to get the object of class example.
THEN WHAT’S DEPENDENCY INJECTION?
Simple, is where an is object provided the dependencies it needs. these dependencies can be objects or values that the object needs at some point in its life cycle. this is where the ioc principle comes in. the object no longer has control over how these dependencies are created, but is given to it by someone else.
see the next example.
we have a interface or contract to implement our class, why ? becouse in our example a chef prepare foods but foods is prepared in its own way.
chef can prepare a lot foods but in this case only we uses 2, you can add whatever you want.
now we’ll do the dependency injection in the constructor the class chef
each food is prepared in its own way, but the chef can add him own things and you dont need add new elements to the cheff class becouse, the class is ready to work with the objects that implement the interface.