DEV Community

Paul Edward
Paul Edward

Posted on

Dependency Injection in PHP

Dependency Injection in PHP

The main advantages of using dependency injection is that it encourages modular programming (The process of subdividing a computer program into separate sub-programs)

The first thing we need to talk about is what dependencies are. So in dependency injection, dependencies are objects that you need to use in your class and injection simply means passing those dependencies into your class, simply put, a dependency is just another object that your class needs to function

There are different ways of injecting dependencies into your classes but the most common way is through the constructor of your class.

*class *UserRepository
{
    *private *$db;
    *private *$config;
    *private *$user;

    *public function *__construct(Database $db, Config $config, User $user)
    {

        $this->db = $db;
        $this->config = $config;
        $this->user = $user;
    }
}
Enter fullscreen mode Exit fullscreen mode

Above is my constructor method, which will bring the dependencies into UserRepository as class properties, so I can use them throughout the class. Rather than instantiating them within my class, I’ll inject them when UserRepository is itself instantiated.

In conjunction with interfaces — you can treat classes as “black boxes” where you can change the dependencies and know that nothing will break!

This seems great right? your code will start to feel more like Lego and less like spaghetti. There are many other benefits too.

Testing becomes easier,

Refactoring becomes easier and

Reusing code is easier.

Life for a coder who uses dependency injection is far easier.



For me, personally, dependency injection has improved my code quality and it is certainly worth implementing.

Enjoy!!

Top comments (0)