Skip to content

Commit 05ecf73

Browse files
committed
minor #20400 Clarify documentation about differences between AutowireIterator and … (lacatoire)
This PR was merged into the 6.4 branch. Discussion ---------- Clarify documentation about differences between AutowireIterator and … Reference [Issue](#20260) Clarify documentation about differences between AutowireIterator and AutowireLocator Commits ------- 7caf0dc Clarify documentation about differences between AutowireIterator and AutowireLocator
2 parents ed79f05 + 7caf0dc commit 05ecf73

File tree

1 file changed

+39
-10
lines changed

1 file changed

+39
-10
lines changed

service_container/service_subscribers_locators.rst

+39-10
Original file line numberDiff line numberDiff line change
@@ -381,19 +381,48 @@ attribute::
381381
:class:`Symfony\\Component\\DependencyInjection\\Attribute\\AutowireLocator`
382382
attribute was introduced in Symfony 6.4.
383383

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.
385390

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

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
393422

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.
397426

398427
.. _service-subscribers-locators_defining-service-locator:
399428

0 commit comments

Comments
 (0)