[英]Symfony2 - Access kernel from a compiler pass
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?
还有另一种方法吗?
As far as I can tell, Kernel isn't available anywhere in a CompilerPass, by default. 据我所知,默认情况下,内核在CompilerPass中的任何位置都不可用。
But you can add it in by doing this: 但你可以通过这样做添加它:
In your AppKernel, pass $this to the bundle the compiler pass is in. 在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
}
What samanime recommends works if you need to whole kernel. 如果你需要整个内核,samanime推荐的是什么。
If you are just interested in some values the kernel contains, it might be sufficient to just use the parameters set by symfony. 如果您只对内核包含的某些值感兴趣,那么仅使用symfony设置的参数就足够了。
Here is a list of available ones: 以下是可用的列表:
Array
(
[0] => kernel.root_dir
[1] => kernel.environment
[2] => kernel.debug
[3] => kernel.name
[4] => kernel.cache_dir
[5] => kernel.logs_dir
[6] => kernel.bundles
[7] => kernel.charset
[8] => kernel.container_class
[9] => kernel.secret
[10] => kernel.http_method_override
[11] => kernel.trusted_hosts
[12] => kernel.trusted_proxies
[13] => kernel.default_locale
)
For instance, the kernel.bundles
contains a list of all registered bundles in the format [bundle => class]
. 例如,
kernel.bundles
包含所有已注册包的列表,格式为[bundle => class]
。
PS: I fetched this list using the following compiler pass: PS:我使用以下编译器传递获取此列表:
<?php
namespace Acme\InfoBundle\DependencyInjection;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
class InfoCompilerPass implements CompilerPassInterface
{
public function process(ContainerBuilder $container)
{
print_r(array_values(array_filter(
array_keys($container->getParameterBag()->all()),
function ($e) {
return strpos($e, 'kernel') === 0;
}
)));
die;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.