Symfony2-通过编译器访问内核

问题描述:

有没有一种方法可以从编译器通道内部访问内核?我已经尝试过了:

Is there a way to access the kernel from inside a compiler pass? I've tried this:

    ...
    public function process(ContainerBuilder $container)
    {
        $kernel = $container->get('kernel');
    }
    ...

这将引发错误.还有另一种方法吗?

This throws an error. Is there another way to do it?

据我所知,默认情况下,内核在CompilerPass中不可用.

As far as I can tell, Kernel isn't available anywhere in a CompilerPass, by default.

但是您可以通过执行以下操作将其添加:

But you can add it in by doing this:

在您的AppKernel中,将$ this传递到编译器通道所在的包中.

In your AppKernel, pass $this to the bundle the compiler pass is in.

  • 向Bundle对象添加一个构造函数,该对象接受Kernel作为参数并将其存储为属性.
  • 在Bundle :: build()函数中,将内核传递到CompilerPass实例.
  • 在您的CompilerPass中,在构造函数中接受内核作为参数并将其存储为属性.
  • 然后,您可以在编译器传递中使用$ this-> kernel.
// app/AppKernel.php
new My\Bundle($this);

// My\Bundle\MyBundle.php
use Symfony\Component\HttpKernel\KernelInterface;

class MyBundle extends Bundle {
protected $kernel;

public function __construct(KernelInterface $kernel)
{
  $this->kernel = $kernel;
}

public function build(ContainerBuilder $container)
{
    parent::build($container);
    $container->addCompilerPass(new MyCompilerPass($this->kernel));
}

// My\Bundle\DependencyInjection\MyCompilerPass.php
use Symfony\Component\HttpKernel\KernelInterface;

class MyCompilerPass implements CompilerPassInterface
protected $kernel;

public function __construct(KernelInterface $kernel)
{
   $this->kernel = $kernel;
}

public function process(ContainerBuilder $container)
{
    // Do something with $this->kernel
}