π§ 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();
β 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();
β
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
Top comments (0)