9951 explained code solutions for 126 technologies


php-symfonyHow to use dependency injection in Symfony with PHP?


Dependency Injection (DI) is a design pattern used to create loosely coupled components in a system. It is a powerful tool for managing class dependencies in Symfony with PHP.

To use DI in Symfony, you need to create a service container and register services in it. Services are objects that can be used by other objects in the system.

Example code

// Create a service container
$container = new Symfony\Component\DependencyInjection\ContainerBuilder();

// Register a service
$container->register('my_service', 'My\Service\Class');

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

Output example

My\Service\Class

Code explanation

  • $container = new Symfony\Component\DependencyInjection\ContainerBuilder(); - creates a service container.
  • $container->register('my_service', 'My\Service\Class'); - registers a service in the container.
  • $myService = $container->get('my_service'); - gets the service from the container.

Helpful links

Edit this code on GitHub