Dependency Injection in PHP (Simple and Practical)
Write testable services by injecting dependencies instead of creating them everywhere.
Liam Cooper
November 14, 2025
1.9k40
Dependency Injection (DI) means: instead of creating dependencies inside a class, you pass them in.
This makes code:
- easier to test
- easier to change later
- more professional
Bad (hard to test)
class OrdersService {
public function createOrder() {
$pdo = new PDO("...");
// hard to test because DB is inside
}
}
Good (inject dependency)
class OrdersService {
public function __construct(private PDO $pdo) {}
public function createOrder() {
// use $this->pdo
}
}
Why this is better
flowchart LR
A[Controller] --> B[OrdersService]
B --> C[(PDO DB)]
Now in tests you can inject a fake PDO or a mock wrapper.
Next: PHP exceptions, custom exceptions, and clean error responses.
#PHP#Architecture#Advanced