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