The DependencyInjection Component

The DependencyInjection Component

The DependencyInjection component implements a PSR-11 compatible service container that allows you to standardize and centralize the way objects are constructed in your application.

For an introduction to Dependency Injection and service containers see Service Container.

Installation

  1. $ composer require symfony/dependency-injection

Note

If you install this component outside of a Symfony application, you must require the vendor/autoload.php file in your code to enable the class autoloading mechanism provided by Composer. Read this article for more details.

Basic Usage

See also

This article explains how to use the DependencyInjection features as an independent component in any PHP application. Read the Service Container article to learn about how to use it in Symfony applications.

You might have a class like the following Mailer that you want to make available as a service:

  1. class Mailer
  2. {
  3. private $transport;
  4. public function __construct()
  5. {
  6. $this->transport = 'sendmail';
  7. }
  8. // ...
  9. }

You can register this in the container as a service:

  1. use Symfony\Component\DependencyInjection\ContainerBuilder;
  2. $containerBuilder = new ContainerBuilder();
  3. $containerBuilder->register('mailer', 'Mailer');

An improvement to the class to make it more flexible would be to allow the container to set the transport used. If you change the class so this is passed into the constructor:

  1. class Mailer
  2. {
  3. private $transport;
  4. public function __construct($transport)
  5. {
  6. $this->transport = $transport;
  7. }
  8. // ...
  9. }

Then you can set the choice of transport in the container:

  1. use Symfony\Component\DependencyInjection\ContainerBuilder;
  2. $containerBuilder = new ContainerBuilder();
  3. $containerBuilder
  4. ->register('mailer', 'Mailer')
  5. ->addArgument('sendmail');

This class is now much more flexible as you have separated the choice of transport out of the implementation and into the container.

Which mail transport you have chosen may be something other services need to know about. You can avoid having to change it in multiple places by making it a parameter in the container and then referring to this parameter for the Mailer service’s constructor argument:

  1. use Symfony\Component\DependencyInjection\ContainerBuilder;
  2. $containerBuilder = new ContainerBuilder();
  3. $containerBuilder->setParameter('mailer.transport', 'sendmail');
  4. $containerBuilder
  5. ->register('mailer', 'Mailer')
  6. ->addArgument('%mailer.transport%');

Now that the mailer service is in the container you can inject it as a dependency of other classes. If you have a NewsletterManager class like this:

  1. class NewsletterManager
  2. {
  3. private $mailer;
  4. public function __construct(\Mailer $mailer)
  5. {
  6. $this->mailer = $mailer;
  7. }
  8. // ...
  9. }

When defining the newsletter_manager service, the mailer service does not exist yet. Use the Reference class to tell the container to inject the mailer service when it initializes the newsletter manager:

  1. use Symfony\Component\DependencyInjection\ContainerBuilder;
  2. use Symfony\Component\DependencyInjection\Reference;
  3. $containerBuilder = new ContainerBuilder();
  4. $containerBuilder->setParameter('mailer.transport', 'sendmail');
  5. $containerBuilder
  6. ->register('mailer', 'Mailer')
  7. ->addArgument('%mailer.transport%');
  8. $containerBuilder
  9. ->register('newsletter_manager', 'NewsletterManager')
  10. ->addArgument(new Reference('mailer'));

If the NewsletterManager did not require the Mailer and injecting it was only optional then you could use setter injection instead:

  1. class NewsletterManager
  2. {
  3. private $mailer;
  4. public function setMailer(\Mailer $mailer)
  5. {
  6. $this->mailer = $mailer;
  7. }
  8. // ...
  9. }

You can now choose not to inject a Mailer into the NewsletterManager. If you do want to though then the container can call the setter method:

  1. use Symfony\Component\DependencyInjection\ContainerBuilder;
  2. use Symfony\Component\DependencyInjection\Reference;
  3. $containerBuilder = new ContainerBuilder();
  4. $containerBuilder->setParameter('mailer.transport', 'sendmail');
  5. $containerBuilder
  6. ->register('mailer', 'Mailer')
  7. ->addArgument('%mailer.transport%');
  8. $containerBuilder
  9. ->register('newsletter_manager', 'NewsletterManager')
  10. ->addMethodCall('setMailer', [new Reference('mailer')]);

You could then get your newsletter_manager service from the container like this:

  1. use Symfony\Component\DependencyInjection\ContainerBuilder;
  2. $containerBuilder = new ContainerBuilder();
  3. // ...
  4. $newsletterManager = $containerBuilder->get('newsletter_manager');

Avoiding your Code Becoming Dependent on the Container

Whilst you can retrieve services from the container directly it is best to minimize this. For example, in the NewsletterManager you injected the mailer service in rather than asking for it from the container. You could have injected the container in and retrieved the mailer service from it but it would then be tied to this particular container making it difficult to reuse the class elsewhere.

You will need to get a service from the container at some point but this should be as few times as possible at the entry point to your application.

Setting up the Container with Configuration Files

As well as setting up the services using PHP as above you can also use configuration files. This allows you to use XML or YAML to write the definitions for the services rather than using PHP to define the services as in the above examples. In anything but the smallest applications it makes sense to organize the service definitions by moving them into one or more configuration files. To do this you also need to install the Config component.

Loading an XML config file:

  1. use Symfony\Component\Config\FileLocator;
  2. use Symfony\Component\DependencyInjection\ContainerBuilder;
  3. use Symfony\Component\DependencyInjection\Loader\XmlFileLoader;
  4. $containerBuilder = new ContainerBuilder();
  5. $loader = new XmlFileLoader($containerBuilder, new FileLocator(__DIR__));
  6. $loader->load('services.xml');

Loading a YAML config file:

  1. use Symfony\Component\Config\FileLocator;
  2. use Symfony\Component\DependencyInjection\ContainerBuilder;
  3. use Symfony\Component\DependencyInjection\Loader\YamlFileLoader;
  4. $containerBuilder = new ContainerBuilder();
  5. $loader = new YamlFileLoader($containerBuilder, new FileLocator(__DIR__));
  6. $loader->load('services.yaml');

Note

If you want to load YAML config files then you will also need to install the Yaml component.

Tip

If your application uses unconventional file extensions (for example, your XML files have a .config extension) you can pass the file type as the second optional parameter of the `load() method:

  1. // ...
  2. $loader->load('services.config', 'xml');

If you do want to use PHP to create the services then you can move this into a separate config file and load it in a similar way:

  1. use Symfony\Component\Config\FileLocator;
  2. use Symfony\Component\DependencyInjection\ContainerBuilder;
  3. use Symfony\Component\DependencyInjection\Loader\PhpFileLoader;
  4. $containerBuilder = new ContainerBuilder();
  5. $loader = new PhpFileLoader($containerBuilder, new FileLocator(__DIR__));
  6. $loader->load('services.php');

You can now set up the newsletter_manager and mailer services using config files:

  • YAML

    1. parameters:
    2. # ...
    3. mailer.transport: sendmail
    4. services:
    5. mailer:
    6. class: Mailer
    7. arguments: ['%mailer.transport%']
    8. newsletter_manager:
    9. class: NewsletterManager
    10. calls:
    11. - setMailer: ['@mailer']
  • XML

    1. <?xml version="1.0" encoding="UTF-8" ?>
    2. <container xmlns="http://symfony.com/schema/dic/services"
    3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    4. xsi:schemaLocation="http://symfony.com/schema/dic/services https://symfony.com/schema/dic/services/services-1.0.xsd">
    5. <parameters>
    6. <!-- ... -->
    7. <parameter key="mailer.transport">sendmail</parameter>
    8. </parameters>
    9. <services>
    10. <service id="mailer" class="Mailer">
    11. <argument>%mailer.transport%</argument>
    12. </service>
    13. <service id="newsletter_manager" class="NewsletterManager">
    14. <call method="setMailer">
    15. <argument type="service" id="mailer"/>
    16. </call>
    17. </service>
    18. </services>
    19. </container>
  • PHP

    1. namespace Symfony\Component\DependencyInjection\Loader\Configurator;
    2. return function(ContainerConfigurator $configurator) {
    3. $configurator->parameters()
    4. // ...
    5. ->set('mailer.transport', 'sendmail')
    6. ;
    7. $services = $configurator->services();
    8. $services->set('mailer', 'Mailer')
    9. // the param() method was introduced in Symfony 5.2.
    10. ->args([param('mailer.transport')])
    11. ;
    12. $services->set('newsletter_manager', 'NewsletterManager')
    13. // In versions earlier to Symfony 5.1 the service() function was called ref()
    14. ->call('setMailer', [service('mailer')])
    15. ;
    16. };

Learn More

This work, including the code samples, is licensed under a Creative Commons BY-SA 3.0 license.