在 symfony 2 中访问 AppKernel 环境变量

2022-08-30 15:07:04

我正在使用symfony 2,我们有2个配置,dev和prod。我需要知道我是否可以在实体或模型内找出哪一个。

我正在寻找类似于AppKernel中的代码.php:

$this->getEnvironment()

如果我可以加载内核来调用它,那就太好了,但我找不到一种方法来做到这一点。在研究了这一点之后,似乎symfony事件可能会返回内核,但我不知道如何或在哪里捕获这些事件,以便我可以在它们上调用getKernel()。http://symfony.com/doc/current/book/internals.html

例如,他们列出了这个例子:

use Symfony\Component\HttpKernel\Event\FilterControllerEvent;

public function onKernelController(FilterControllerEvent $event)
{
    $controller = $event->getController();
    // ...

    // the controller can be changed to any PHP callable
    $event->setController($controller);
}

我不清楚该把这个代码块放在哪里。在我看来,它应该进入内核,如果我有内核,我就不会有这个问题。

我的问题是,有没有一种简单的方法可以让我从服务或模型中确定我是在内核中设置的“dev”还是“prod”。谢谢


答案 1

控制台生成的默认实体类不会继承任何内容。这意味着它们在任何方面都不是“ContainerAware”。

一般来说,我认为他们不应该。我以为这取决于你在做什么,但你可以通过一些基本的依赖注入来处理这个问题。

在控制器中:

$entity = new \Your\Bundle\Entity\Foo(
  $this->container->get( 'kernel' )->getEnvironment()
);

然后在src/Your/Bundle/Entity/Foo中.php

private $env;

public function __construct( $env=null )
{
  $this->env = $env;
}

这对你有用吗?

附言:您发布的事件侦听器是针对控制器的,而不是针对任意类的。


答案 2

也可以将其作为参数获取。如果你看一下这个类,你会发现一个公开所有内核参数的方法。\Symfony\Component\HttpKernel\KernelgetKernelParameters()

/**
 * Returns the kernel parameters.
 *
 * @return array An array of kernel parameters
 */
protected function getKernelParameters()
{
    $bundles = array();
    foreach ($this->bundles as $name => $bundle) {
        $bundles[$name] = get_class($bundle);
    }

    return array_merge(
        array(
            'kernel.root_dir' => realpath($this->rootDir) ?: $this->rootDir,
            'kernel.environment' => $this->environment,
            'kernel.debug' => $this->debug,
            'kernel.name' => $this->name,
            'kernel.cache_dir' => realpath($this->getCacheDir()) ?: $this->getCacheDir(),
            'kernel.logs_dir' => realpath($this->getLogDir()) ?: $this->getLogDir(),
            'kernel.bundles' => $bundles,
            'kernel.charset' => $this->getCharset(),
            'kernel.container_class' => $this->getContainerClass(),
        ),
        $this->getEnvParameters()
    );
}

因此,在文件中,您可以获取环境,而在容器感知类中,您可以通过执行以下操作来获取它:services.yml%kernel.environment%

$this->getContainer()->getParameter('kernel.environment');

请参阅github上的内核.php类


推荐