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.

<?php
class UserRepository
{
private $db;
private $config;
private $users;
public function __construct(Database $db, Config $config, User $users)
{
$this->db = $db;
$this->config = $config;
$this->users = $users;
}
public function allUser(){
foreach ($this->users->all() as $user){
echo $user->name. '\n';
}
}
}



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

Enjoy!!

Image of Quadratic

Free AI chart generator

Upload data, describe your vision, and get Python-powered, AI-generated charts instantly.

Try Quadratic free

Top comments (0)

AWS Security LIVE! Stream

Stream AWS Security LIVE!

See how AWS is redefining security by design with simple, seamless solutions on Security LIVE!

Learn More

👋 Kindness is contagious

Dive into this thoughtful article, cherished within the supportive DEV Community. Coders of every background are encouraged to share and grow our collective expertise.

A genuine "thank you" can brighten someone’s day—drop your appreciation in the comments below!

On DEV, sharing knowledge smooths our journey and strengthens our community bonds. Found value here? A quick thank you to the author makes a big difference.

Okay