Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Clarify documentation about differences between AutowireIterator and … #20400

Open
wants to merge 1 commit into
base: 6.4
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
49 changes: 39 additions & 10 deletions service_container/service_subscribers_locators.rst
Original file line number Diff line number Diff line change
Expand Up @@ -381,19 +381,48 @@ attribute::
:class:`Symfony\\Component\\DependencyInjection\\Attribute\\AutowireLocator`
attribute was introduced in Symfony 6.4.

.. note::
The AutowireIterator Attribute
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Variant of the ``AutowireLocator`` that specifically provides an iterable of services
based on a tag. This allows you to collect all services with a particular tag into
an iterable, which can be useful when you need to iterate over a set of services
rather than retrieving them individually.

To receive an iterable instead of a service locator, you can switch the
:class:`Symfony\\Component\\DependencyInjection\\Attribute\\AutowireLocator`
attribute to
:class:`Symfony\\Component\\DependencyInjection\\Attribute\\AutowireIterator`
attribute.
For example, if you want to collect all the handlers for different command types,
you can use the ``AutowireIterator`` attribute to automatically inject all services
tagged with a specific tag::

// src/CommandBus.php
namespace App;

use App\CommandHandler\BarHandler;
use App\CommandHandler\FooHandler;
use Psr\Container\ContainerInterface;
use Symfony\Component\DependencyInjection\Attribute\AutowireIterator;

class CommandBus
{
public function __construct(
#[AutowireIterator('command_handler')]
private iterable $handlers, // Collects all services tagged with 'command_handler'
) {
}

.. versionadded:: 6.4
public function handle(Command $command): mixed
{
foreach ($this->handlers as $handler) {
if ($handler->supports($command)) {
return $handler->handle($command);
}
}
}
}

.. versionadded:: 6.4

The
:class:`Symfony\\Component\\DependencyInjection\\Attribute\\AutowireIterator`
attribute was introduced in Symfony 6.4.
The
:class:`Symfony\\Component\\DependencyInjection\\Attribute\\AutowireIterator`
attribute was introduced in Symfony 6.4.

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

Expand Down
Loading