Dependency Injection in PHP: Decoupling Classes

In the previous post, we learned that Reflection allows PHP to inspect classes at runtime. But Reflection only tells us what a class needs. It doesn't create those dependencies. That's the job of Dependency Injection (DI). Let's start with an example. class UserController { private UserService $service; public function __construct() { $this->service = new UserService(); } } At first glance, this looks fine. But imagine UserService changes. Today it has no constructor. Tomorrow it requires a repository. class UserService { public function __construct( private UserRepository $repository ) {} } Now your controller breaks. You must go back and edit it. class UserController { public function __construct() { $this->service = new UserService( new UserRepository() ); } } A month later... UserRepository now needs a database connection. new UserService( new UserRepository( new DatabaseConnection(...) ) ); Every change in the dependency chain forces you to revisit code that shouldn't even care how those objects are created. This is called tight coupling. Instead, let the class declare what it needs. class UserController { public function __construct( private UserService $service ) {} } Now the controller doesn't know—or care—how UserService is created. It simply receives one that's ready to use. That's Dependency Injection. The responsibility of creating objects is moved outside the class. In the next post, we'll answer the obvious question: If the controller no longer creates UserService... who does? #PHP #Laravel #DependencyInjection #SOLID #BackendDevelopment

  • graphical user interface

Impressive ❤️❤️

Like
Reply

To view or add a comment, sign in

Explore content categories