June 4, 2025
What Is Dependency Injection?
Dependency Injection is a design pattern used to pass dependencies (services/objects) into a class, rather than the class creating them itself.
π§ Why Use Dependency Injection?
- β Promotes loose coupling
- β Improves testability
- β Follows Single Responsibility Principle
- β Makes code easier to maintain and extend
π§± Without Dependency Injection (tight coupling):
class UserController {
protected $userService;
public function __construct() {
$this->userService = new UserService(); // tightly coupled
}
}
β With Dependency Injection (loose coupling):
class UserController {
protected $userService;
public function __construct(UserService $userService) {
$this->userService = $userService;
}
}
Then you inject UserService
when instantiating UserController
:
phpCopyEdit$userService = new UserService();
$userController = new UserController($userService);
π Real-World Example (Laravel-style):
In Laravel, constructor injection is common:
class InvoiceController extends Controller {
public function __construct(private InvoiceService $invoiceService) {}
public function generate() {
return $this->invoiceService->createInvoice();
}
}
Laravelβs service container automatically resolves InvoiceService
!
π§ Interview Tip:
“Dependency Injection decouples classes and promotes modular design. I prefer constructor injection for required dependencies and setter injection for optional ones.”
Comments are closed.