有没有办法从编译器传递内部访问内核?我试过这个:
...
public function process(ContainerBuilder $container)
{
$kernel = $container->get('kernel');
}
...
这会引发错误。还有另一种方法吗?
最佳答案
据我所知,默认情况下,内核在 CompilerPass 中的任何地方都不可用。
但是你可以通过这样做来添加它:
在您的 AppKernel 中,将 $this 传递给编译器传递所在的包。
// 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
}
关于Symfony2 - 从编译器 channel 访问内核,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13852611/