Skip to content

Service Method Calls and Setter Injection

Warning: You are browsing the documentation for Symfony 3.x, which is no longer maintained.

Read the updated version of this page for Symfony 7.1 (the current stable version).

Tip

If you're using autowiring, you can use @required to automatically configure method calls.

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:

1
2
3
4
5
6
7
8
# app/config/services.yml
services:
    AppBundle\Service\MessageGenerator:
        # ...
        calls:
            - method: setLogger
              arguments:
                  - '@logger'
This work, including the code samples, is licensed under a Creative Commons BY-SA 3.0 license.
TOC
    Version