Dependency Injection in PHP

Dependency injection is the process by which one object provides the dependencies of another object. Dependency injection is a software design approach that avoids hard-coded dependencies and allows you to change dependencies at runtime and compile time.

Lets take a look along with the examples. Lets say we have a Food class that will supply dependency to Dinner Class.

After that, lets create a dinner class without dependency injection first.

In the above style of Dinner class, we have hardcoded food class that is bad in coupling and not well dependency injected. Lets fix our dinner class using dependency injection.

Now, we have added a constructor to be injected the necessary food dependency object. The code is now loosely coupled and not hardcoded in dinner class anymore.

By Yuuma.




tel. 06-6454-8833(平日 10:00~17:00)