|
4 | 4 | Service Closures
|
5 | 5 | ================
|
6 | 6 |
|
| 7 | +.. versionadded:: 5.4 |
| 8 | + The ``service_closure()`` function was introduced in Symfony 5.4. |
| 9 | + |
7 | 10 | This feature wraps the injected service into a closure allowing it to be
|
8 | 11 | lazily loaded when and if needed.
|
9 | 12 | This is useful if the service being injected is a bit heavy to instantiate
|
@@ -70,17 +73,37 @@ argument of type ``service_closure``:
|
70 | 73 | namespace Symfony\Component\DependencyInjection\Loader\Configurator;
|
71 | 74 |
|
72 | 75 | use App\Service\MyService;
|
73 |
| - use Symfony\Component\DependencyInjection\Argument\ServiceClosureArgument; |
74 |
| - use Symfony\Component\DependencyInjection\Reference; |
75 | 76 |
|
76 | 77 | return function (ContainerConfigurator $configurator) {
|
77 | 78 | $services = $configurator->services();
|
78 | 79 |
|
79 | 80 | $services->set(MyService::class)
|
80 |
| - ->args([new ServiceClosureArgument(new Reference('mailer'))]); |
| 81 | + ->args([service_closure('mailer')]); |
| 82 | +
|
| 83 | + // In case the dependency is optional |
| 84 | + // $services->set(MyService::class) |
| 85 | + // ->args([service_closure('mailer')->ignoreOnInvalid()]); |
81 | 86 | };
|
82 | 87 |
|
83 | 88 | .. seealso::
|
84 | 89 |
|
85 | 90 | Another way to inject services lazily is via a
|
86 | 91 | :doc:`service locators </service_container/service_subscribers_locators>`.
|
| 92 | + |
| 93 | +Using a Service Closures in a Compiler Pass |
| 94 | +------------------------------------------- |
| 95 | + |
| 96 | +In :doc:`compiler passes </service_container/compiler_passes>` you can create |
| 97 | +a service closure by wrapping the service reference into an instance of |
| 98 | +:class:`Symfony\\Component\\DependencyInjection\\Argument\\ServiceClosureArgument`:: |
| 99 | + |
| 100 | + use Symfony\Component\DependencyInjection\Argument\ServiceClosureArgument; |
| 101 | + use Symfony\Component\DependencyInjection\ContainerBuilder; |
| 102 | + use Symfony\Component\DependencyInjection\Reference; |
| 103 | + |
| 104 | + public function process(ContainerBuilder $container): void |
| 105 | + { |
| 106 | + // ... |
| 107 | + |
| 108 | + $myService->addArgument(new ServiceClosureArgument(new Reference('mailer'))); |
| 109 | + } |
0 commit comments