@@ -247,10 +247,45 @@ Defining a Service Locator
247
247
--------------------------
248
248
249
249
To manually define a service locator and inject it to another service, create an
250
- argument of type ``service_locator ``:
250
+ argument of type ``service_locator ``.
251
+
252
+ Consider the following ``CommandBus `` class where you want to inject
253
+ some services into it via a service locator::
254
+
255
+ // src/HandlerCollection.php
256
+ namespace App;
257
+
258
+ use Symfony\Component\DependencyInjection\ServiceLocator;
259
+
260
+ class CommandBus
261
+ {
262
+ public function __construct(ServiceLocator $locator)
263
+ {
264
+ }
265
+ }
266
+
267
+ Symfony allows you to inject the service locator using YAML/XML/PHP configuration
268
+ or directly via PHP attributes:
251
269
252
270
.. configuration-block ::
253
271
272
+ .. conde-block :: php-attributes
273
+
274
+ // src/CommandBus.php
275
+ namespace App;
276
+
277
+ use Symfony\C omponent\D ependencyInjection\A ttribute\T aggedLocator;
278
+ use Symfony\C omponent\D ependencyInjection\S erviceLocator;
279
+
280
+ class CommandBus
281
+ {
282
+ public function __construct(
283
+ // creates a service locator with all the services tagged with 'app.handler'
284
+ #[TaggedLocator('app.handler')] ServiceLocator $locator
285
+ ) {
286
+ }
287
+ }
288
+
254
289
.. code-block :: yaml
255
290
256
291
# config/services.yaml
@@ -304,6 +339,10 @@ As shown in the previous sections, the constructor of the ``CommandBus`` class
304
339
must type-hint its argument with ``ContainerInterface ``. Then, you can get any of
305
340
the service locator services via their ID (e.g. ``$this->locator->get('App\FooCommand') ``).
306
341
342
+ .. versionadded :: 5.3
343
+
344
+ The ``#[TaggedLocator] `` attribute was introduced in Symfony 5.3 and requires PHP 8.
345
+
307
346
Reusing a Service Locator in Multiple Services
308
347
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
309
348
@@ -457,7 +496,7 @@ will share identical locators among all the services referencing them::
457
496
// ...
458
497
'logger' => new Reference('logger'),
459
498
];
460
-
499
+
461
500
$myService = $container->findDefinition(MyService::class);
462
501
463
502
$myService->addArgument(ServiceLocatorTagPass::register($container, $locateableServices));
0 commit comments