How DI works inside the MVC?

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 UserController is responsible for knowing how to create its own dependencies (UserService).
  • The UserService is 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 where UserController is 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:

  1. Resolves that you need a UserController.
  2. Checks the UserController‘s constructor (or other injection points) to see what dependencies it requires.
  3. Recursively resolves those dependencies. For example, if UserController needs UserService:
    • It checks if UserService has been registered.
    • If not, it figures out how to create it.
    • To create UserService, it sees that UserService needs UserRepository.
    • It figures out how to create UserRepository (perhaps it was registered with specific arguments like a database connection).
  4. Injects the resolved dependencies into the object being created.
  5. 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.