8000 [DI] Document PHP-DSL service_closure() function · symfony/symfony-docs@8ab82c2 · GitHub
[go: up one dir, main page]

Skip to content

Commit 8ab82c2

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

File tree

1 file changed

+27
-3
lines changed

1 file changed

+27
-3
lines changed

service_container/service_closures.rst

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

7+
.. versionadded:: 5.4
8+
9+
The ``service_closure()`` function was introduced in Symfony 5.4.
10+
711
This feature wraps the injected service into a closure allowing it to be
812
lazily loaded when and if needed.
913
This is useful if the service being injected is a bit heavy to instantiate
@@ -70,17 +74,37 @@ argument of type ``service_closure``:
7074
namespace Symfony\Component\DependencyInjection\Loader\Configurator;
7175
7276
use App\Service\MyService;
73-
use Symfony\Component\DependencyInjection\Argument\ServiceClosureArgument;
74-
use Symfony\Component\DependencyInjection\Reference;
7577
7678
return function (ContainerConfigurator $configurator) {
7779
$services = $configurator->services();
7880
7981
$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()]);
8187
};
8288
8389
.. seealso::
8490

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

Comments
 (0)
0