Skip to content

Commit 005216a

Browse files
committed
[DI] Document PHP-DSL service_closure() function
1 parent 73125ee commit 005216a

File tree

1 file changed

+26
-3
lines changed

1 file changed

+26
-3
lines changed

service_container/service_closures.rst

Lines changed: 26 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,9 @@
44
Service Closures
55
================
66

7+
.. versionadded:: 5.4
8+
The ``service_closure()`` function was introduced in Symfony 5.4.
9+
710
This feature wraps the injected service into a closure allowing it to be
811
lazily loaded when and if needed.
912
This is useful if the service being injected is a bit heavy to instantiate
@@ -70,17 +73,37 @@ argument of type ``service_closure``:
7073
namespace Symfony\Component\DependencyInjection\Loader\Configurator;
7174
7275
use App\Service\MyService;
73-
use Symfony\Component\DependencyInjection\Argument\ServiceClosureArgument;
74-
use Symfony\Component\DependencyInjection\Reference;
7576
7677
return function (ContainerConfigurator $configurator) {
7778
$services = $configurator->services();
7879
7980
$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()]);
8186
};
8287
8388
.. seealso::
8489

8590
Another way to inject services lazily is via a
8691
: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

Comments
 (0)