The Dependency Injection Container is the tool that makes objects ready to pass by automatically creating them and their required dependencies.
Imagine you have a UserController that needs a UserService, and the UserService needs a UserRepository.
If you were to create these manually without a dependency injection container, your UserController creation might look something like this:
php
// Without a DI Container (Manual Dependency Creation)
// 1. Create the deepest dependency first
$userRepository = new UserRepository(/* DB Connection */);
// 2. Create the service, passing its dependency
$userService = new UserService($userRepository);
// 3. Create the controller, passing its dependency
$userController = new UserController($userService);
// Now you can use $userController
As you can see:
- The
UserControlleris responsible for knowing how to create its own dependencies (UserService). - The
UserServiceis responsible for knowing how to create its dependencies (UserRepository). - This creates a tight coupling. If
UserService‘s constructor changes, you have to update the code whereUserControlleris created. - Managing these dependencies becomes very complex in larger applications with many interconnected objects.
The Role of the Dependency Injection Container
A Dependency Injection (DI) Container automates the process of creating objects and their dependencies. It acts as a central registry and factory for your application’s objects.
Instead of manually creating and wiring up dependencies, you register your classes and their relationships with the container. Then, when you ask the container for an object (e.g., UserController), it automatically:
- Resolves that you need a
UserController. - Checks the
UserController‘s constructor (or other injection points) to see what dependencies it requires. - Recursively resolves those dependencies. For example, if
UserControllerneedsUserService:- It checks if
UserServicehas been registered. - If not, it figures out how to create it.
- To create
UserService, it sees thatUserServiceneedsUserRepository. - It figures out how to create
UserRepository(perhaps it was registered with specific arguments like a database connection).
- It checks if
- Injects the resolved dependencies into the object being created.
- Returns the fully constructed object.
At this stage we need to know the ReflectionClass of PHP. This is built in class of PHP library and it gives all information about a class. It is having many method to know more about the class.
Check this short video to know more about ReflectionClass.
