在symfony 2中访问AppKernel环境变量 [英] Accessing the AppKernel environment variable in symfony 2

查看:56
本文介绍了在symfony 2中访问AppKernel环境变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm Using symfony 2 and we have 2 configurations, dev and prod. I need to know if I can find out which one im using inside an Entity or Model.

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

I'm looking for something similar to this code found in AppKernel.php:

$this->getEnvironment()

如果我可以加载内核来调用它,那将很棒,但是我找不到解决方法。经过研究,symfony事件似乎可以返回内核,但是我不知道如何或在何处捕获这些事件,因此可以在它们上调用getKernel()。 http://symfony.com/doc/current/book/internals.html

If I could load the Kernel to call this that would be great but I can't find a way to do this. After looking into this it appears that symfony events may return the Kernel but I don't know how or where to capture these events so that I can call getKernel() on them. http://symfony.com/doc/current/book/internals.html

例如,他们列出了以下示例:

For example, they list this example:

使用Symfony\Component\HttpKernel\Event\ \FilterControllerEvent;

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);
}

我不清楚将这段代码放在哪里。在我看来,它应该放在内核中,如果我拥有内核,我就不会遇到这个问题。

Its unclear to me where to put this block of code. It seems to me that it should go in the Kernel, and if I had the Kernel I wouldn't be having this problem.

我的问题是,是否有一个简单的选择通过服务或模型确定我是处于内核中设置的 dev还是 prod的方式。
谢谢

My question is, is there an easy way for me to determine if I'm in 'dev' or 'prod' as set in the Kernel, from a Service or Model. Thanks

推荐答案

控制台生成的默认实体类不继承任何东西。这意味着它们绝不是 ContainerAware。

The default entity classes generated by the console don't inherit anything. This means they aren't "ContainerAware" in any way.

通常来说,我认为它们不应该。我认为这取决于您在做什么,但是您可以通过一些基本的依赖注入来解决这个问题

And generally speaking, I don't think they should be. I supposed it depends on what you're doing but you could handle this with some basic dependency injection

在控制器中:

$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;
}

这项工作对您有用吗?

PS您发布的事件侦听器适用于控制器-不适用于任意类。

这篇关于在symfony 2中访问AppKernel环境变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆