Skip to content

Instantly share code, notes, and snippets.

@docteurklein
Created October 25, 2013 13:33
Show Gist options
  • Save docteurklein/7154758 to your computer and use it in GitHub Desktop.
Save docteurklein/7154758 to your computer and use it in GitHub Desktop.
Decorate services with other services
services:
security.voter.logger:
class: App\Security\Voter\Logger
arguments: [~, '@logger']
public: false
tags:
- { name: monolog.logger, channel: voter }
security.voter.aww:
class: App\Security\Voter\Aww
public: false
tags:
- { name: security.voter, priority: 257 }
- { name: decorated, by: security.voter.logger }
security.voter.rooh:
class: App\Security\Voter\Rooh
public: false
tags:
- { name: security.voter, priority: 257 }
- { name: decorated, by: security.voter.logger }
<?php
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\DefinitionDecorator;
use Symfony\Component\DependencyInjection\Reference;
class SetServiceDecoratorPass implements CompilerPassInterface
{
public function process(ContainerBuilder $container)
{
foreach ($container->findTaggedServiceIds('decorated') as $id => $attributes) {
foreach ($attributes as $attribute) {
if (!isset($attribute['by']) || !$container->hasDefinition($by = $attribute['by'])) {
continue;
}
$decorated = $container->getDefinition($id);
$container->setDefinition($id.'.parent', $decorated);
$decorator = new DefinitionDecorator($by);
$container->setDefinition($id.'.decorator', $decorator);
$container->setAlias($id, $id.'.decorator');
$decorator->replaceArgument(0, new Reference($id.'.parent'));
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment