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.”