In my previous article, I have explained DI (Dependency Injection). In this article, I will explain how we can use Inversion of Control in PHP to reduce complexity that comes with DI.
Every design pattern has its positive and negative aspects, DI can make it easier to automate the testing process using unit testing frameworks. But, on the other side, DI can introduce extra complexity in your code that makes it more verbose and less readable. For example:
$subdep = new SubDep(); //dependency required for Dep1 class.
$dep1 = new Dep1($subdep); //creating Dep1 by injecting its dependency
$dep2 = new Dep2(); //creating Dep2.
$dep3 = new Dep3(); //creating Dep3
$instance = new SomeClass($dep1,$dep2,$dep3); // injecting required dependencies
As you can see,
SomeClass requires three dependencies, whereas
Dep1 has its own dependency (more complexity). So the point is, if you are dealing with lot of dependencies in your application, you could end up writing and repeating a lot of code throughout your application. To subdue this problem, we use another design pattern called as Inversion of Control Container.
In software engineering, inversion of control (IoC) is a programming technique, expressed here in terms of object-oriented programming, in which object coupling is bound at run time by an assembler object and is typically not known at compile time using static analysis.
Inversion Of Control in PHP: Dependency Management
What I have learned so far is, the more you try to explain inversion of control, the more it gets complicated. So, instead of digging in further details, its better to work through an example. Read more…