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