Understanding Dependency Injection

Do you often hear about this concept but avoid to understand what’s about? Give it a shot!

Miguel Loureiro
Coding skills
Published in
4 min readMar 16, 2014

--

Understanding Dependency Injection

Do you often hear about this concept but avoid to understand what’s about ? Give it a shot!

Sometimes this words seem to be scary and you just think “oh well, I’ll learn that later”. It happened to me also. Turns out, it’s a very simple concept that will dramatically increase your code quality and maintainability, so why not start understanding it now ?

The concept and the benefits

Dependency injection is all about removing hard-coded dependencies from your classes. Simple as that!

By removing them, your code will be more decoupled and it will be one big step to follow the well known SRP ( Single Responsibility Principle ) for good object-oriented design making it testable and maintainable.

But what is a dependency ?

Let’s read this PHP code and try to identify the dependencies it has.

<?phpclass OccurrenceManager {public function create($occurrenceData)
{
// creates a connection and a validator
$connection = new DatabaseConnection();
$validator = new OccurrenceValidator();
if($validator->check($occurrenceData)) { /* insert occurrence data to the db*/

$connection->insert(‘OccurrenceTable’,$data);

/* returns a json response */

return new JSONResponse([‘msg’ => ‘Success’]);
} else {
/* in case of error validating returns json with errors */

return new JSONResponse([‘msg’ => $validator->errors()]);
}
}
}?>

It’s actually pretty easy to understand the concept of dependency. A dependency, as the name suggests, is something your class depends on to perform a specific task. We can easily identify the dependencies then, and they are:

  • DatabaseConnection
  • OccurrenceValidator
  • JSONResponse

What’s the problem if your code is like this ? Let’s imagine you want to have a different persistence layer or you want to return a XMLResponse instead of a JSONResponse. Since, the dependencies are hard coded in the class your code is not maintainable.

Good, you now understand what is a dependency and the problems they bring!

Inject it!

The main idea is that your class should be responsible for one thing only, so it shouldn’t care about how it connects to the database, or how it creates a response. Stick with this, inject your dependencies!

There are two ways of doing this and we’ll see both.

Constructor Injection

<?phpclass OccurrenceManager {    protected $connection;
protected $validator;
protected $response;
public function __construct($con, $val, $resp)
{
$this->connection = $con;
$this->validator = $val;
$this->response = $resp;
}
public function create($occurrenceData)
{
$validator = $this->validator;
$db = $this->connection;
$rsp = $this->response;
if($validator->check($occurrenceData)) {

// insert occurrence data to the db
$db->insert(‘OccurrenceTable’,$data);

// returns some response
return $rsp->message([‘msg’ => ‘Success’]);
} else {

// in case of error return errors
return $rsp->message([‘msg’ => $validator->errors()]);
}
}
}
/* i.e. */
$manager = new OccurrenceManager($dbConn, $occValidator, $xmlRsp);
?>

Using this method we are injecting the dependencies when the class constructor runs.

Setter Injection

<?phpclass OccurrenceManager {    protected $connection;
protected $validator;
protected $response;
public function __construct()
{

}
public function create($occurrenceData)
{
$validator = $this->validator;
$db = $this->connection;
$rsp = $this->response;
if($validator->check($occurrenceData)) {

// insert occurrence data to the db
$db->insert(‘OccurrenceTable’,$data);

// returns some response
return $rsp->message([‘msg’ => ‘Success’]);
} else {

// in case of error return errors
return $rsp->message([‘msg’ => $validator->errors()]);
}
}
public function setConnection($con)
{
$this->connection = $con;
}
public function setValidator($validator)
{
$this->validator = $validator;
}
public function setResponse($response)
{
$this->response = $response;
}
}
/* i.e. */
$manager = new OccurrenceManager();
$manager->setConnection($dbConn);
$manager->setValidator($occValidator);
$manager->setResponse($xmlRsp);
?>

Above we are using setters to inject the dependencies.

Can you see the benefits of this ? Like you saw, if for instance you wish to give a XML response instead of a JSON response, just inject the corresponding dependency instead of hardcoding your class. ☺

The downside

You will face a problem when using dependency injection. While decoupling more and more your code it’ll get hard to manage all the dependencies and you’ll have lots of code just for injecting the dependencies, in our example if we want to create an instance of OccurrenceManager we need to do this.

$db = new DatabaseConnection($someConfig);
$validator = new OccurrenceValidator();
$response = new XMLResponse();
$manager = new OccurrenceManager($db, $validator, $response);

The solution for this is to use a D.I.C. (Dependency Injection Container).

Next week we will talk about how to implement a simple container and the benefits it gives us.

Hope this article was of use to you guys! If it was, care to share it and give feedback ! ☺

--

--

Miguel Loureiro
Coding skills

Product & Technology, entrepreneur, early-stage investor and advisor, occasional blogger