Skip to content

[AutowireLocator] Using #[AutowireLocator] with tagged class #20934

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

Open
wants to merge 2 commits into
base: 7.2
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
71 changes: 71 additions & 0 deletions service_container/service_subscribers_locators.rst
Original file line number Diff line number Diff line change
Expand Up @@ -397,6 +397,77 @@ attribute::
}
}

Using AutowireLocator with tagged class

Another way to use
:class:`Symfony\\Component\\DependencyInjection\\Attribute\\AutowireLocator`
attribute is location class tagged with a specific :doc:`tag </service_container/tags>`

Tagging allows you to add classes without having to explicitly list classes in
:class:`Symfony\\Component\\DependencyInjection\\Attribute\\AutowireLocator`
attribute

It is also possible to use the #[AutoconfigureTag] attribute directly on the base class or interface and all classes implementing this interface will be automatically tagged and included in
:class:`Symfony\\Component\\DependencyInjection\\Attribute\\AutowireLocator`
attribute::

// src/CommandBus.php
namespace App;

use Psr\Container\ContainerInterface;
use Symfony\Component\DependencyInjection\Attribute\AutowireLocator;

class CommandBus
{
public function __construct(
#[AutowireLocator("command_handler")]
private ContainerInterface $handlers,
) {
}

public function handle(Object $command, string $handlerClassName): mixed
{
if ($this->handlers->has($handlerClassName)) {
$handler = $this->handlers->get($handlerClassName);

return $handler->handle($command);
}
}
}

// src/CommandHandler/CommandHandlerInterface.php
namespace App\CommandHandler;

use Symfony\Component\DependencyInjection\Attribute\AutoconfigureTag;

#[AutoconfigureTag('command_handler')]
interface CommandHandlerInterface
{
public function handle(object $command);
}

// src/CommandHandler/FooHandler.php
namespace App\CommandHandler;

class FooHandler implements CommandHandlerInterface
{
public function handle(object $command)
{
dump("Foo", $command);
}
}

// src/CommandHandler/BarHandler.php
namespace App\CommandHandler;

class BarHandler implements CommandHandlerInterface
{
public function handle(object $command)
{
dump("Bar", $command);
}
}

.. _service-locator_autowire-iterator:

The AutowireIterator Attribute
Expand Down