Skip to content

Instantly share code, notes, and snippets.

@jmikola
Created January 18, 2011 20:35
Show Gist options
  • Save jmikola/785089 to your computer and use it in GitHub Desktop.
Save jmikola/785089 to your computer and use it in GitHub Desktop.
Retrieving tagged services after the Symfony2 DIC has already been compiled
<?php
namespace OpenSky\Bundle\MainBundle\DependencyInjection\Compiler;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Reference;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
class AggregatedTaggedServicesPass implements CompilerPassInterface
{
/**
* @see Symfony\Component\DependencyInjection\Compiler.CompilerPassInterface::process()
*/
public function process(ContainerBuilder $container)
{
if (!$container->hasDefinition('tagged_service_holder')) {
return;
}
$taggedServiceHolder = $container->getDefinition('tagged_service_holder');
foreach ($container->findTaggedServiceIds('custom.tag') as $id => $attributes) {
$taggedServiceHolder->addMethodCall('push', array(new Reference($id)));
}
}
}
<?php
/* Elsewhere in your container-aware code, you can simply iterate across the
* tagged service holder (a SplDoublyLinkedList in this example) in lieu of
* calling findTaggedServiceIds().
*/
foreach ($container->get('tagged_service_holder') as $taggedService) {
// do something with the service
}
<?php
namespace OpenSky\Bundle\MainBundle;
use OpenSky\Bundle\MainBundle\DependencyInjection\Compiler\AggregatedTaggedServicesPass;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\HttpKernel\Bundle\Bundle;
class MainBundle extends Bundle
{
/**
* @see Symfony\Component\HttpKernel\Bundle.Bundle::registerExtensions()
*/
public function registerExtensions(ContainerBuilder $container)
{
parent::registerExtensions($container);
$container->addCompilerPass(new AggregatedTaggedServicesPass());
}
}
<?php
namespace OpenSky\Bundle\MainBundle\DependencyInjection;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Definition;
use Symfony\Component\DependencyInjection\Extension\Extension;
class MainExtension extends Extension
{
public function configLoad($config, ContainerBuilder $container)
{
if (!$container->hasDefinition('tagged_service_holder')) {
$taggedServiceHolder = new Definition();
$taggedServiceHolder->setClass('SplDoublyLinkedList');
$container->setDefinition('tagged_service_holder', $taggedServiceHolder);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment