WARNING: You are browsing the documentation for Symfony 2.7 which is not maintained anymore. Consider upgrading your projects to Symfony 4.1.

Service Method Calls and Setter Injection

2.7 version

Service Method Calls and Setter InjectionΒΆ

Usually, you'll want to inject your dependencies via the constructor. But sometimes, especially if a dependency is optional, you may want to use "setter injection". For example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
namespace AppBundle\Service;

use Psr\Log\LoggerInterface;

class MessageGenerator
{
    private $logger;

    public function setLogger(LoggerInterface $logger)
    {
        $this->logger = $logger;
    }

    // ...
}

To configure the container to call the setLogger method, use the calls key:

  • YAML
    1
    2
    3
    4
    5
    6
    7
    8
    # app/config/services.yml
    services:
        app.message_generator:
            # ...
            calls:
                - method: setLogger
                  arguments:
                      - '@logger'
    
  • XML
     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    <!-- app/config/services.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"
        xsi:schemaLocation="http://symfony.com/schema/dic/services
            http://symfony.com/schema/dic/services/services-1.0.xsd">
    
        <services>
            <service id="app.message_generator" class="AppBundle\Service\MessageGenerator">
                <!-- ... -->
                <call method="setLogger">
                    <argument type="service" id="logger" />
                </call>
            </service>
        </services>
    </container>
    
  • PHP
    1
    2
    3
    4
    5
    6
    // app/config/services.php
    use AppBundle\Service\MessageGenerator;
    use Symfony\Component\DependencyInjection\Reference;
    
    $container->register('app.message_generator', 'AppBundle\Service\MessageGenerator')
        ->addMethodCall('setLogger', array(new Reference('logger')));
    

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