I can create multiple services with the load
method.
… but I want each service to have the same tag, with some attributes that can be inferred from the service class itself:
// config/services.php
return static function (ContainerConfigurator $container): void {
$services = $container->services()
->defaults()
->autoconfigure()
->autowire();
$services->load('App\Components\', __DIR__ . '/../src/App/Components')
->tag('mytag', [
'key' => null, // this should depend on service class
]);
}
Does Symfony offer a way to accomplish this?
I would, instead (i don’t like both solutions):
In services.php
, manually loop src/App/Components
and use the reflection to extract the information I need, then call set
to register the service
// config/services.php
$files = (new Finder())->files()->name('*.php')->in(__DIR__ . '/../src/App/Components');
foreach ($files as $file) {
// Extract the FQCN
$reflection = new ReflectionClass($fqcn);
$services->set($reflection->getName())
->tag('mytag', ['key' => $reflection->getShortName());
}
Another solution would be to assign a “temporary tag”, then use a compiler pass to get the information I need and assign the final tag to it:
// config/services.php
$services->load('App\Components\', __DIR__ . '/../src/App/Components')
->tag('temp_tag');
// DependencyInjection/TagPass.php
foreach ($container->findTaggedServiceIds('temp_tag') as $id => $tags) {
$definition = $container->getDefinition($id);
$reflection = new ReflectionClass($definition->getClass());
$definition
->clearTags()
->addTag('mytag', ['key' => $reflection->getShortName()]);
}