DEV Community

Ahmed Raza Idrisi
Ahmed Raza Idrisi

Posted on

PHP Dependency Injection (DI)

πŸ”§ What Is Dependency Injection (DI)?
Dependency Injection means giving an object everything it needs (its dependencies), instead of letting the object create them by itself.

πŸ’‘ Real-Life Analogy
Imagine you're a chef (your class), and you need a knife (a dependency) to chop vegetables.

❌ Without DI: You go and buy your own knife inside the kitchen (tight coupling).

βœ… With DI: Someone gives you the knife when you enter (loose coupling, more flexible).

βœ… Simple Example Without DI (Tight Coupling)

class Engine {
    public function start() {
        return "Engine started";
    }
}

class Car {
    protected $engine;

    public function __construct() {
        $this->engine = new Engine(); // Car creates the Engine itself
    }

    public function drive() {
        return $this->engine->start() . " and car is moving.";
    }
}

$car = new Car();
echo $car->drive();

Enter fullscreen mode Exit fullscreen mode

❌ Problem:
Car is tightly dependent on the Engine class.

Hard to test, replace, or mock the engine.

βœ… Now With Dependency Injection (Loose Coupling)

class Engine {
    public function start() {
        return "Engine started";
    }
}

class Car {
    protected $engine;

    // Engine is injected from outside
    public function __construct(Engine $engine) {
        $this->engine = $engine;
    }

    public function drive() {
        return $this->engine->start() . " and car is moving.";
    }
}

// We create Engine separately and inject it into Car
$engine = new Engine();
$car = new Car($engine);

echo $car->drive();

Enter fullscreen mode Exit fullscreen mode

βœ… Benefits:
Car doesn't care how the engine is made.

You can easily swap the Engine with something else (e.g. mock in tests).

This is what frameworks like Laravel do automatically with the service container

Types of Dependency Injection

Top comments (0)