Skip to content

Instantly share code, notes, and snippets.

@colinfrei
Created November 7, 2012 07:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save colinfrei/4030056 to your computer and use it in GitHub Desktop.
Save colinfrei/4030056 to your computer and use it in GitHub Desktop.
Generic class to allow overwriting a service
<?php
namespace Symfony\Component\DependencyInjection\Compiler;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Alias;
/**
* Overwrites a service with an alias to a new service, and injects the old service as a parent of the new one
*
* @author Christophe Coevoet <stof@notk.org>
*/
class ServiceAliasPass implements CompilerPassInterface
{
private $oldService;
private $newService;
private $renameTo;
public function __construct($oldService, $newService, $renameTo = null)
{
$this->oldService = $oldService;
$this->newService = $newService;
$this->renameTo = $renameTo;
if (!$this->renameTo) {
$this->renameTo = $this->newService . '.parent';
}
}
public function process(ContainerBuilder $container)
{
if ($container->hasAlias($this->oldService)) {
// Service we're overwriting is an alias.
// Register a private alias for this service to inject it as the parent
$container->setAlias($this->renameTo, new Alias((string) $container->getAlias($this->oldService), false));
} else {
// Service we're overwriting is a definition.
// Register it again as a private service to inject it as the parent
$definition = $container->getDefinition($this->oldService);
$definition->setPublic(false);
$container->setDefinition($this->renameTo, $definition);
}
$container->setAlias($this->oldService, $this->newService);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment