Answer the question
In order to leave comments, you need to log in
How to store tag alias in the service itself in Symfony2?
There is classic documentation on Working with tags in Symfony2 services .
In my task, with the help of CompilerPass, I transfer all my transport services protegized in the same way to some kind of Provider (TransportChain in the example from the documentation).
It is described like this:
<service id="example.test1_transport" class="Example\Transport">
<tag name="example.transport" alias="transport1"/>
</service>
<service id="example.test2_transport" class="Example\Transport">
<tag name="example.transport" alias="transport2"/>
</service>
Answer the question
In order to leave comments, you need to log in
There are three ways
to pass an argument to a service through a configuration :
1. To a constructor
2. Through a setter
3. Directly to a property
It is necessary to determine what to do with services in the future. Using an alias in this case looks redundant, since you can use a unique service id.
Let's use the last example from the page:
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\Reference;
class TransportCompilerPass implements CompilerPassInterface
{
public function process(ContainerBuilder $container)
{
if (!$container->hasDefinition('acme_mailer.transport_chain')) {
return;
}
// Получаем определение сервиса для хранения объектов транспорта
$definition = $container->getDefinition(
'acme_mailer.transport_chain'
);
// Получаем все сервисы транспорта то тегу
$taggedServices = $container->findTaggedServiceIds(
'acme_mailer.transport'
);
// Задаем инъекцию каждого транспорта в хранилище
foreach ($taggedServices as $id => $tagAttributes) {
// Вложенный цикл перебирает все теги каждого сервиса, здесь надо быть аккуратным
foreach ($tagAttributes as $attributes) {
$definition->addMethodCall(
'addTransport',
array(new Reference($id), $attributes["alias"])
);
}
}
}
}
<services>
<service id="acme_mailer.transport_chain" class="TransportChain">
<call method="setDI">
<argument type="service" id="service_container" />
</call>
</service>
</services>
$transports = array_keys($container->findTaggedServiceIds('acme_mailer.transport' ));
$definition->addMethodCall('setTransports', [ $transports ]);
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question