Skip to content

Instantly share code, notes, and snippets.

@bangpound
Created July 28, 2015 14:05
Show Gist options
  • Save bangpound/bdebfaf4822527e9857d to your computer and use it in GitHub Desktop.
Save bangpound/bdebfaf4822527e9857d to your computer and use it in GitHub Desktop.
Symfony closure compiler pass
<?php
namespace DependencyInjection\Compiler;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
class ClosureCompilerPass implements CompilerPassInterface
{
private $pass;
public function __construct($pass)
{
$this->pass = $pass;
}
public function process(ContainerBuilder $container)
{
call_user_func($this->pass, $container);
}
}
<?php
namespace SomeBundle;
use DependencyInjection\Compiler\ClosureCompilerPass;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Reference;
use Symfony\Component\HttpKernel\Bundle\Bundle;
class SomeBundle extends Bundle
{
public function build(ContainerBuilder $container)
{
parent::build($container);
$container->addCompilerPass(new ClosureCompilerPass(function (ContainerBuilder $container) {
// example from http://symfony.com/doc/current/components/dependency_injection/tags.html
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 => $tags) {
foreach ($tags as $attributes) {
$definition->addMethodCall(
'addTransport',
array(new Reference($id), $attributes["alias"])
);
}
}
}));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment