@@ -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
@@ -305,22 +340,6 @@ As shown in the previous sections, the constructor of the ``CommandBus`` class
305
340
must type-hint its argument with ``ContainerInterface ``. Then, you can get any of
306
341
the service locator services via their ID (e.g. ``$this->locator->get('App\FooCommand') ``).
307
342
308
- The same behavior can be achieved using the ``#[TaggedLocator] `` attribute. This
309
- attribute must be directly used on a ``ServiceLocator `` argument::
310
-
311
- // src/HandlerCollection.php
312
- namespace App;
313
-
314
- use Symfony\Component\DependencyInjection\Attribute\TaggedLocator;
315
- use Symfony\Component\DependencyInjection\ServiceLocator;
316
-
317
- class HandlerCollection
318
- {
319
- public function __construct(#[TaggedLocator('app.handler')] ServiceLocator $locator)
320
- {
321
- }
322
- }
323
-
324
343
.. versionadded :: 5.3
325
344
326
345
The ``#[TaggedLocator] `` attribute was introduced in Symfony 5.3 and requires PHP 8.
0 commit comments