Skip to content

Commit c573cbb

Browse files
committed
Merge branch '7.2' into 7.3
* 7.2: Tweaks Clarify documentation about differences between AutowireIterator and AutowireLocator
2 parents 16d7666 + 77d695d commit c573cbb

File tree

1 file changed

+39
-9
lines changed

1 file changed

+39
-9
lines changed

Diff for: service_container/service_subscribers_locators.rst

+39-9
Original file line numberDiff line numberDiff line change
@@ -320,10 +320,10 @@ This is done by having ``getSubscribedServices()`` return an array of
320320
The above example requires using ``3.2`` version or newer of ``symfony/service-contracts``.
321321

322322
.. _service-locator_autowire-locator:
323-
.. _service-locator_autowire-iterator:
323+
.. _the-autowirelocator-and-autowireiterator-attributes:
324324

325-
The AutowireLocator and AutowireIterator Attributes
326-
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
325+
The AutowireLocator Attribute
326+
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
327327

328328
Another way to define a service locator is to use the
329329
:class:`Symfony\\Component\\DependencyInjection\\Attribute\\AutowireLocator`
@@ -397,13 +397,43 @@ attribute::
397397
}
398398
}
399399

400-
.. note::
400+
.. _service-locator_autowire-iterator:
401401

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+
}
407437

408438
.. _service-subscribers-locators_defining-service-locator:
409439

0 commit comments

Comments
 (0)