The DependencyInjection Component
Note
If you install this component outside of a Symfony application, you mustrequire the file in your code to enable the classautoloading mechanism provided by Composer. Readthis article for more details.
This article explains how to use the DependencyInjection features as anindependent component in any PHP application. Read the article to learn about how to use it in Symfony applications.
You might have a class like the following Mailer
thatyou want to make available as a service:
- class Mailer
- {
- private $transport;
- public function __construct()
- {
- $this->transport = 'sendmail';
- }
- // ...
- }
You can register this in the container as a service:
- 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 allowthe container to set the transport
used. If you change the classso this is passed into the constructor:
- class Mailer
- {
- private $transport;
- public function __construct($transport)
- {
- $this->transport = $transport;
- }
- // ...
- }
Then you can set the choice of transport in the container:
- 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 oftransport out of the implementation and into the container.
- 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 asa dependency of other classes. If you have a NewsletterManager
classlike this:
When defining the newsletter_manager
service, the service doesnot exist yet. Use the Reference
class to tell the container to inject themailer
service when it initializes the newsletter manager:
- 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 injectingit was only optional then you could use setter injection instead:
- 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:
- 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 service from the containerlike this:
- use Symfony\Component\DependencyInjection\ContainerBuilder;
- $containerBuilder = new ContainerBuilder();
- // ...
- $newsletterManager = $containerBuilder->get('newsletter_manager');
Whilst you can retrieve services from the container directly it is bestto minimize this. For example, in the NewsletterManager
you injectedthe mailer
service in rather than asking for it from the container.You could have injected the container in and retrieved the mailer
servicefrom it but it would then be tied to this particular container making itdifficult to reuse the class elsewhere.
As well as setting up the services using PHP as above you can also useconfiguration files. This allows you to use XML or YAML to write the definitionsfor the services rather than using PHP to define the services as in theabove examples. In anything but the smallest applications it makes senseto organize the service definitions by moving them into one or more configurationfiles. To do this you also need to installthe Config component.
Loading an XML config file:
- 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:
Note
If you want to load YAML config files then you will also need to install.
Tip
If your application uses unconventional file extensions (for example, yourXML files have a .config
extension) you can pass the file type as thesecond optional parameter of the load()
method:
- // ...
- $loader->load('services.config', 'xml');
If you do want to use PHP to create the services then you can move thisinto a separate config file and load it in a similar way:
- 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 services usingconfig files:
- YAML
- parameters:
- # ...
- mailer.transport: sendmail
- services:
- mailer:
- class: Mailer
- arguments: ['%mailer.transport%']
- newsletter_manager:
- class: NewsletterManager
- calls:
- - [setMailer, ['@mailer']]
- XML
- <?xml version="1.0" encoding="UTF-8" ?>
- <container xmlns="http://symfony.com/schema/dic/services"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- <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>
- PHP
- namespace Symfony\Component\DependencyInjection\Loader\Configurator;
- return function(ContainerConfigurator $configurator) {
- $configurator->parameters()
- // ...
- ->set('mailer.transport', 'sendmail')
- ;
- $services = $configurator->services();
- $services->set('mailer', 'Mailer')
- ->args(['%mailer.transport%'])
- ;
- $services->set('newsletter_manager', 'NewsletterManager')
- ->call('setMailer', [ref('mailer')])
- ;
- };
- Compiling the Container
- The Symfony 3.3 DI Container Changes Explained (autowiring, _defaults, etc)
- Defining Services Dependencies Automatically (Autowiring)
- How to Work with Compiler Passes
- How to Debug the Service Container & List Services
- How to Inject Values Based on Complex Expressions
- How to Import Configuration Files/Resources
- Lazy Services
- How to Manage Common Dependencies with Parent Services
- How to Decorate Services
- How to Define Non Shared Services
- How to Work with Service Tags