DEV Community

Joshua Johnson for UA1 Labs

Posted on • Originally published at ua1.us on

FireDI – When Should I Use Dependency Injection?

FireDI Project

UA1 Labs has been at this for a while and has made many wonder tools for developers to help keep them focused on the development they are doing. When we interact with other developers and talk with them about dependency injection, there is a bit of confusion on when they should be using it. This post will help answer some of the reasons you may want to consider using dependency injection within you PHP projects.

First off, what is dependency injection anyway?

Well dependency injection is a design pattern that goes way back in the history of software engineering. Its been around and while and has had many different implementations. In its simplest form, dependency injection is a fancy term for making sure that the class you are about to instantiate has the dependencies instantiated for you already.

<?php
class A
{
    public function __construct($dependency)
    {
        $this->dep = $dependency;
    }
}

$dependency = new Dependency();
$classA = new A($dependency);

In the example above class A needs some sort of dependency resolved before it can be instantiated. Dependency injection is that simple! You may have noticed though that this can be a pain in the butt to have to always be resolving dependencies every time you want to get an instance of class A.

<?php
$classA = $firedi->get('A');

In the example above, you will notice that I’m getting the same class A instantiated, but I do not need to first resolve the dependency. FireDI is instead handling that behind the scenes for me! That is what a typical dependency injection library will do for you.

So when do I need to use a dependency injection library?

The answer is simple. When you find it helpful! I know, I know…that isn’t very helpful for me to tell you. You are looking for the solid, “…this is when you should use a dependency injection library.” Why don’t I just tell you the benefits of using one. If these benefits add value to your project, then I would say use a dependency injection library!

Benefit 1. Off the bat, you can see that you will be writing a lot less code for getting instantiated objects. The class A example I shared above, is only the tip of the iceberg with regards to dependency resolution. The more complex a project gets, the more dependencies you will have to resolve in order to get the object you are trying to access. A dependency injection library will track all of these dependencies for you and resolve them as they need to be resolved.

Benefit 2. The second benefit to using a dependency injection library has to do with automated testing. Whether that is unit testing or integrated testing. Having the ability to switch out class definitions for mock definitions makes your life in testing so much easier.

The post FireDI – When Should I Use Dependency Injection? appeared first on UA1 Labs.

Top comments (0)