@@ -320,10 +320,10 @@ This is done by having ``getSubscribedServices()`` return an array of
320
320
The above example requires using ``3.2 `` version or newer of ``symfony/service-contracts ``.
321
321
322
322
.. _service-locator_autowire-locator :
323
- .. _ service-locator_autowire-iterator :
323
+ .. _ the-autowirelocator-and-autowireiterator-attributes :
324
324
325
- The AutowireLocator and AutowireIterator Attributes
326
- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
325
+ The AutowireLocator Attribute
326
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
327
327
328
328
Another way to define a service locator is to use the
329
329
:class: `Symfony\\ Component\\ DependencyInjection\\ Attribute\\ AutowireLocator `
@@ -397,13 +397,43 @@ attribute::
397
397
}
398
398
}
399
399
400
- .. note : :
400
+ .. _ service-locator_autowire-iterator :
401
401
402
- To receive an iterable instead of a service locator, you can switch the
403
- :class: `Symfony\\ Component\\ DependencyInjection\\ Attribute\\ AutowireLocator `
404
- attribute to
405
- :class: `Symfony\\ Component\\ DependencyInjection\\ Attribute\\ AutowireIterator `
406
- attribute.
402
+ The AutowireIterator Attribute
403
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
404
+
405
+ A variant of ``AutowireLocator `` that injects an iterable of services tagged
406
+ with a specific :doc: `tag </service_container/tags >`. This is useful to loop
407
+ over a set of tagged services instead of retrieving them individually.
408
+
409
+ For example, to collect all handlers for different command types, use the
410
+ ``AutowireIterator `` attribute and pass the tag used by those services::
411
+
412
+ // src/CommandBus.php
413
+ namespace App;
414
+
415
+ use App\CommandHandler\BarHandler;
416
+ use App\CommandHandler\FooHandler;
417
+ use Psr\Container\ContainerInterface;
418
+ use Symfony\Component\DependencyInjection\Attribute\AutowireIterator;
419
+
420
+ class CommandBus
421
+ {
422
+ public function __construct(
423
+ #[AutowireIterator('command_handler')]
424
+ private iterable $handlers, // collects all services tagged with 'command_handler'
425
+ ) {
426
+ }
427
+
428
+ public function handle(Command $command): mixed
429
+ {
430
+ foreach ($this->handlers as $handler) {
431
+ if ($handler->supports($command)) {
432
+ return $handler->handle($command);
433
+ }
434
+ }
435
+ }
436
+ }
407
437
408
438
.. _service-subscribers-locators_defining-service-locator :
409
439
0 commit comments