Sobes.tech
Middle

What is a dependency injection (DI) container?

sobes.tech AI

Answer from AI

Dependency Injection (DI container) is an object that manages the creation and lifecycle of objects and their dependencies. It implements the Inversion of Control (IoC) principle.

Main functions:

  • Registration: Describing how to create and configure objects.
  • Resolving: Obtaining an instance of an object by its name or type.
  • Dependency Injection: Automatically passing required objects (dependencies) into the constructor or methods of the requested object.

Advantages of using:

  • Reduces code coupling.
  • Simplifies testing (dependencies can be easily replaced).
  • More flexible application configuration.
  • Centralized management of dependencies.

Example of registering and obtaining a service in pseudocode:

// Registering a service
$container->set('myService', function($container) {
    // Creating a MyService object and passing dependencies
    $dependency = $container->get('myDependency');
    return new MyService($dependency);
});

// Getting the service
$service = $container->get('myService');