Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commitab6d0d0

Browse files
committed
[DI] Document PHP-DSL service_closure() function
1 parentafd5e85 commitab6d0d0

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
@@ -75,17 +79,37 @@ argument of type ``service_closure``:
7579
namespace Symfony\Component\DependencyInjection\Loader\Configurator;
7680
7781
use App\Service\MyService;
78-
use Symfony\Component\DependencyInjection\Argument\ServiceClosureArgument;
79-
use Symfony\Component\DependencyInjection\Reference;
8082
8183
return function (ContainerConfigurator $containerBuilder) {
8284
$services = $containerBuilder->services();
8385
8486
$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()]);
8692
};
8793
8894
..seealso::
8995

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

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp