有没有办法从编译器传递中访问内核?我试过这个:
...
public function process(ContainerBuilder $container)
{
$kernel = $container->get('kernel');
}
...
Run Code Online (Sandbox Code Playgroud)
这会引发错误.还有另一种方法吗?
sam*_*ime 13
据我所知,默认情况下,内核在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
}
Run Code Online (Sandbox Code Playgroud)
小智 9
如果你需要整个内核,samanime推荐的是什么.
如果您只对内核包含的某些值感兴趣,那么仅使用symfony设置的参数就足够了.
以下是可用的列表:
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
)
Run Code Online (Sandbox Code Playgroud)
例如,它kernel.bundles
包含格式中所有已注册包的列表[bundle => class]
.
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;
}
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
1999 次 |
最近记录: |