@@ -381,19 +381,48 @@ attribute::
381
381
:class: `Symfony\\ Component\\ DependencyInjection\\ Attribute\\ AutowireLocator `
382
382
attribute was introduced in Symfony 6.4.
383
383
384
- .. note ::
384
+ The AutowireIterator Attribute
385
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
386
+ Variant of the ``AutowireLocator `` that specifically provides an iterable of services
387
+ based on a tag. This allows you to collect all services with a particular tag into
388
+ an iterable, which can be useful when you need to iterate over a set of services
389
+ rather than retrieving them individually.
385
390
386
- To receive an iterable instead of a service locator, you can switch the
387
- :class: `Symfony\\ Component\\ DependencyInjection\\ Attribute\\ AutowireLocator `
388
- attribute to
389
- :class: `Symfony\\ Component\\ DependencyInjection\\ Attribute\\ AutowireIterator `
390
- attribute.
391
+ For example, if you want to collect all the handlers for different command types,
392
+ you can use the ``AutowireIterator `` attribute to automatically inject all services
393
+ tagged with a specific tag::
394
+
395
+ // src/CommandBus.php
396
+ namespace App;
397
+
398
+ use App\CommandHandler\BarHandler;
399
+ use App\CommandHandler\FooHandler;
400
+ use Psr\Container\ContainerInterface;
401
+ use Symfony\Component\DependencyInjection\Attribute\AutowireIterator;
402
+
403
+ class CommandBus
404
+ {
405
+ public function __construct(
406
+ #[AutowireIterator('command_handler')]
407
+ private iterable $handlers, // Collects all services tagged with 'command_handler'
408
+ ) {
409
+ }
391
410
392
- .. versionadded :: 6.4
411
+ public function handle(Command $command): mixed
412
+ {
413
+ foreach ($this->handlers as $handler) {
414
+ if ($handler->supports($command)) {
415
+ return $handler->handle($command);
416
+ }
417
+ }
418
+ }
419
+ }
420
+
421
+ .. versionadded :: 6.4
393
422
394
- The
395
- :class: `Symfony\\ Component\\ DependencyInjection\\ Attribute\\ AutowireIterator `
396
- attribute was introduced in Symfony 6.4.
423
+ The
424
+ :class: `Symfony\\ Component\\ DependencyInjection\\ Attribute\\ AutowireIterator `
425
+ attribute was introduced in Symfony 6.4.
397
426
398
427
.. _service-subscribers-locators_defining-service-locator :
399
428
0 commit comments