Service Method Calls and Setter Injection
Edit this pageWarning: You are browsing the documentation for Symfony 4.1, which is no longer maintained.
Read the updated version of this page for Symfony 6.3 (the current stable version).
Service Method Calls and Setter Injection
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 App\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
# config/services.yaml
services:
App\Service\MessageGenerator:
# ...
calls:
- method: setLogger
arguments:
- '@logger'
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
<!-- 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\Service\MessageGenerator">
<!-- ... -->
<call method="setLogger">
<argument type="service" id="logger" />
</call>
</service>
</services>
</container>
1 2 3 4 5 6
// config/services.php
use App\Service\MessageGenerator;
use Symfony\Component\DependencyInjection\Reference;
$container->register(MessageGenerator::class)
->addMethodCall('setLogger', [new Reference('logger')]);