Dependency Injection in simple words

Vineeth Vijayan
Vineeth Vijayan
Published in
2 min readMay 16, 2020
Photo by Ross Sneddon on Unsplash

The word dependency means dependent on something. For example lets say our economy is dependent on oil exports.

Lets assume there are two classes, class X and class Y. If class X is using some functionality of class Y, then we can say class X has dependency of class Y.

Normally when we use one class in another class, it is done by creating object of first class with “new” keyword in the second class. Like following code

class Student {  private $studentName;  public __construct($studentName){    $this->studentName = $studentName;  }}
class School {
private $student; private $schoolName; public __construct($schoolName, $studentName){ $this->schoolName = $schoolName; $this->student = new Student($studentName)

}
}

In above mentioned code, as said in the comment. If we create object of another class this way. This makes both classes tightly coupled, it is against SOLID principles. Also this will make it hard to scale the app in case of large scale applications. Because since both classes are dependent, if one class is updated we may need to update all classes dependent with this one.

Dependency injection solves this issue. In this method, the dependency is injected via constructor of the dependent class or in our case the School class. Lets see how its done

class Student {  private $studentName;  public __construct($studentName){    $this->studentName = $studentName;  }}

class School {
private $student; private $schoolName; public __construct($schoolName, Student $student){

$this->schoolName = $schoolName;
$this->student = $student;

}
}

If you ask if this a big deal? I would say yes and no, because dependency injection is useful in long term, large scale projects. But as a programmer we should know the standards. Coding standards make our code reusable, maintainable and reliable. Like Uncle Bob always said, if doctors and engineers are doing it, why not us?

Happy Coding!

Love this article? Click here to buy me a coffee :)

--

--

Vineeth Vijayan
Vineeth Vijayan

Software Engineer | Scribbler | Loves coding and movies | Passive Reader | Lazy Blogger