Skip to content
  • About
    • What is Symfony?
    • Community
    • News
    • Contributing
    • Support
  • Documentation
    • Symfony Docs
    • Symfony Book
    • Screencasts
    • Symfony Bundles
    • Symfony Cloud
    • Training
  • Services
    • SensioLabs Professional services to help you with Symfony
    • Platform.sh for Symfony Best platform to deploy Symfony apps
    • SymfonyInsight Automatic quality checks for your apps
    • Symfony Certification Prove your knowledge and boost your career
    • Blackfire Profile and monitor performance of your apps
  • Other
  • Blog
  • Download
sponsored by SensioLabs
  1. Home
  2. Documentation
  3. The DependencyInjection Component
  • Documentation
  • Book
  • Reference
  • Bundles
  • Cloud

Table of Contents

  • Installation
  • Basic Usage
  • Avoiding your Code Becoming Dependent on the Container
  • Setting up the Container with Configuration Files
  • Learn More

The DependencyInjection Component

Edit this page

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
2
3
4
5
6
7
8
9
10
11
class Mailer
{
    private $transport;

    public function __construct()
    {
        $this->transport = 'sendmail';
    }

    // ...
}

You can register this in the container as a service:

1
2
3
4
use Symfony\Component\DependencyInjection\ContainerBuilder;

$containerBuilder = new ContainerBuilder();
$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
2
3
4
5
6
7
8
9
10
11
class Mailer
{
    private $transport;

    public function __construct($transport)
    {
        $this->transport = $transport;
    }

    // ...
}

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

1
2
3
4
5
6
use Symfony\Component\DependencyInjection\ContainerBuilder;

$containerBuilder = new ContainerBuilder();
$containerBuilder
    ->register('mailer', 'Mailer')
    ->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
2
3
4
5
6
7
use Symfony\Component\DependencyInjection\ContainerBuilder;

$containerBuilder = new ContainerBuilder();
$containerBuilder->setParameter('mailer.transport', 'sendmail');
$containerBuilder
    ->register('mailer', 'Mailer')
    ->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
2
3
4
5
6
7
8
9
10
11
class NewsletterManager
{
    private $mailer;

    public function __construct(\Mailer $mailer)
    {
        $this->mailer = $mailer;
    }

    // ...
}

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
2
3
4
5
6
7
8
9
10
11
12
13
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Reference;

$containerBuilder = new ContainerBuilder();

$containerBuilder->setParameter('mailer.transport', 'sendmail');
$containerBuilder
    ->register('mailer', 'Mailer')
    ->addArgument('%mailer.transport%');

$containerBuilder
    ->register('newsletter_manager', 'NewsletterManager')
    ->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
2
3
4
5
6
7
8
9
10
11
class NewsletterManager
{
    private $mailer;

    public function setMailer(\Mailer $mailer)
    {
        $this->mailer = $mailer;
    }

    // ...
}

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
2
3
4
5
6
7
8
9
10
11
12
13
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Reference;

$containerBuilder = new ContainerBuilder();

$containerBuilder->setParameter('mailer.transport', 'sendmail');
$containerBuilder
    ->register('mailer', 'Mailer')
    ->addArgument('%mailer.transport%');

$containerBuilder
    ->register('newsletter_manager', 'NewsletterManager')
    ->addMethodCall('setMailer', [new Reference('mailer')]);

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

1
2
3
4
5
6
7
use Symfony\Component\DependencyInjection\ContainerBuilder;

$containerBuilder = new ContainerBuilder();

// ...

$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
2
3
4
5
6
7
use Symfony\Component\Config\FileLocator;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Loader\XmlFileLoader;

$containerBuilder = new ContainerBuilder();
$loader = new XmlFileLoader($containerBuilder, new FileLocator(__DIR__));
$loader->load('services.xml');

Loading a YAML config file:

1
2
3
4
5
6
7
use Symfony\Component\Config\FileLocator;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Loader\YamlFileLoader;

$containerBuilder = new ContainerBuilder();
$loader = new YamlFileLoader($containerBuilder, new FileLocator(__DIR__));
$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
2
3
4
5
6
7
use Symfony\Component\Config\FileLocator;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Loader\PhpFileLoader;

$containerBuilder = new ContainerBuilder();
$loader = new PhpFileLoader($containerBuilder, new FileLocator(__DIR__));
$loader->load('services.php');

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

1
2
3
4
5
6
7
8
9
10
11
12
parameters:
    # ...
    mailer.transport: sendmail

services:
    mailer:
        class:     Mailer
        arguments: ['%mailer.transport%']
    newsletter_manager:
        class:     NewsletterManager
        calls:
            - [setMailer, ['@mailer']]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<?xml version="1.0" encoding="UTF-8" ?>
<container xmlns="http://symfony.com/schema/dic/services"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://symfony.com/schema/dic/services
        https://symfony.com/schema/dic/services/services-1.0.xsd"
>
    <parameters>
        <!-- ... -->
        <parameter key="mailer.transport">sendmail</parameter>
    </parameters>

    <services>
        <service id="mailer" class="Mailer">
            <argument>%mailer.transport%</argument>
        </service>

        <service id="newsletter_manager" class="NewsletterManager">
            <call method="setMailer">
                <argument type="service" id="mailer"/>
            </call>
        </service>
    </services>
</container>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
namespace Symfony\Component\DependencyInjection\Loader\Configurator;

return static function (ContainerConfigurator $containerConfigurator) {
    $containerConfigurator->parameters()
        // ...
        ->set('mailer.transport', 'sendmail')
    ;

    $services = $containerConfigurator->services();
    $services->set('mailer', 'Mailer')
        ->args(['%mailer.transport%'])
    ;

    $services->set('mailer', 'Mailer')
        // the param() method was introduced in Symfony 5.2.
        ->args([param('mailer.transport')])
    ;

    $services->set('newsletter_manager', 'NewsletterManager')
        // In versions earlier to Symfony 5.1 the service() function was called ref()
        ->call('setMailer', [service('mailer')])
    ;
};

Learn More

  • Compiling the Container
  • Container Building Workflow
  • How to Create Service Aliases and Mark Services as Private
  • Defining Services Dependencies Automatically (Autowiring)
  • Service Method Calls and Setter Injection
  • How to Work with Compiler Passes
  • How to Configure a Service with a Configurator
  • How to Debug the Service Container & List Services
  • How to work with Service Definition Objects
  • How to Inject Values Based on Complex Expressions
  • Using a Factory to Create Services
  • How to Import Configuration Files/Resources
  • Types of Injection
  • Lazy Services
  • How to Make Service Arguments/References Optional
  • How to Manage Common Dependencies with Parent Services
  • How to Retrieve the Request from the Service Container
  • Service Closures
  • How to Decorate Services
  • Service Subscribers & Locators
  • How to Define Non Shared Services
  • How to Inject Instances into the Container
  • How to Work with Service Tags
This work, including the code samples, is licensed under a Creative Commons BY-SA 3.0 license.
TOC
    Version
    We stand with Ukraine.
    Version:

    Symfony 5.4 is backed by

    Put the code quality back at the heart of your project

    Put the code quality back at the heart of your project

    Symfony Code Performance Profiling

    Symfony Code Performance Profiling

    Symfony footer

    ↓ Our footer now uses the colors of the Ukrainian flag because Symfony stands with the people of Ukraine.

    Avatar of Ahmad El-Bardan, a Symfony contributor

    Thanks Ahmad El-Bardan for being a Symfony contributor

    2 commits • 8 lines changed

    View all contributors that help us make Symfony

    Become a Symfony contributor

    Be an active part of the community and contribute ideas, code and bug fixes. Both experts and newcomers are welcome.

    Learn how to contribute

    Symfony™ is a trademark of Symfony SAS. All rights reserved.

    • What is Symfony?

      • Symfony at a Glance
      • Symfony Components
      • Case Studies
      • Symfony Releases
      • Security Policy
      • Logo & Screenshots
      • Trademark & Licenses
      • symfony1 Legacy
    • Learn Symfony

      • Symfony Docs
      • Symfony Book
      • Reference
      • Bundles
      • Best Practices
      • Training
      • eLearning Platform
      • Certification
    • Screencasts

      • Learn Symfony
      • Learn PHP
      • Learn JavaScript
      • Learn Drupal
      • Learn RESTful APIs
    • Community

      • SymfonyConnect
      • Support
      • How to be Involved
      • Code of Conduct
      • Events & Meetups
      • Projects using Symfony
      • Downloads Stats
      • Contributors
      • Backers
    • Blog

      • Events & Meetups
      • A week of symfony
      • Case studies
      • Cloud
      • Community
      • Conferences
      • Diversity
      • Documentation
      • Living on the edge
      • Releases
      • Security Advisories
      • SymfonyInsight
      • Twig
      • SensioLabs
    • Services

      • SensioLabs services
      • Train developers
      • Manage your project quality
      • Improve your project performance
      • Host Symfony projects

      Deployed on

    Follow Symfony

    Search by Algolia