php 使用 Symfony 检查控制器内是否处于“开发”模式
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12998060/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Check if in "dev" mode inside a Controller with Symfony
提问by JeanValjean
When using dev mode with a Symfony2.xapplication, one usually works in locale. Hence, such function does not works as expected (for instance, try to get the current IP under localhost). This could be a problem, e.g. when one try to use such ip-based web service. Hence, I just want to know how to check inside a controller if the Symfony2 application is running in devmode or not. In that way one can set the behavior of the controller depending by the mode.
在Symfony2.x应用程序中使用开发模式时,通常在语言环境中工作。因此,此类功能无法按预期工作(例如,尝试获取 localhost 下的当前 IP)。这可能是一个问题,例如,当您尝试使用这种基于 ip 的 Web 服务时。因此,我只想知道如何在控制器内部检查 Symfony2 应用程序是否在开发模式下运行。通过这种方式,可以根据模式设置控制器的行为。
Any idea?
任何的想法?
回答by tolgap
To get the current environment in a Controlleryou can use:
要在 a 中获取当前环境,Controller您可以使用:
$this->container->getParameter('kernel.environment');
So you just put that in an if()statement to check if it equals to dev.
所以你只要把它放在一个if()语句中来检查它是否等于dev.
回答by Damaged Organic
As of Symfony 2.5it could be done as:
从 Symfony 2.5 开始,它可以这样做:
$this->container->get('kernel')->getEnvironment();
Directly asking Kernel of it's environment looks nicer than searching for parameter.
直接询问内核它的环境看起来比搜索参数更好。
回答by Veve
Since you want to know if you are in dev mode (not necessarilly the environment named "dev"), you can retrieve the kernel from the service container and check the isDebugmethod return:
由于您想知道您是否处于开发模式(不一定是名为“dev”的环境),您可以从服务容器中检索内核并检查isDebug方法返回:
$kernel = $this->get('kernel');
$devMode = $kernel->isDebug();
As noted in the documentation(emphasis is mine),
如文档中所述(重点是我的),
Important, but unrelated to the topic of environments is the
trueorfalseargument as the second argument to theAppKernelconstructor. This specifies if the application should run in "debug mode". Regardless of the environment, a Symfony application can be run with debug mode set to true or false. This affects many things in the application, such as displaying stacktraces on error pages or if cache files are dynamically rebuilt on each request. Though not a requirement, debug mode is generally set to true for the dev and test environments and false for the prod environment.Internally, the value of the debug mode becomes the kernel.debug parameter used inside the service container.
重要但与环境主题无关的是
trueorfalse参数作为AppKernel构造函数的第二个参数。这指定应用程序是否应在“调试模式”下运行。无论环境如何,Symfony 应用程序都可以在调试模式设置为 true 或 false 的情况下运行。这会影响应用程序中的许多事情,例如在错误页面上显示堆栈跟踪,或者是否在每个请求上动态重建缓存文件。尽管不是必需的,但调试模式通常在开发和测试环境中设置为 true,在生产环境中设置为 false。在内部,调试模式的值成为服务容器内部使用的 kernel.debug 参数。
回答by Tomá? Votruba
Symfony 3.3/4/5+ Solution
Symfony 3.3/4/5+ 解决方案
Here is 2017 and Symfony 3.3+version using Constructor Injection.
这是使用构造函数注入的2017 和 Symfony 3.3+版本。
Instead of passing you whole application (= container), you could pass only the parameter you need:
您可以只传递您需要的参数,而不是传递整个应用程序(= 容器):
1. Service config
1.服务配置
# app/config/services.yml
services:
_defaults:
autowire: true
App\Controller\SomeController:
arguments: ['%kernel.environment%']
If you don't understand this syntax, check this post explaining Symfony DI news in before/after examples.
如果您不理解此语法,请查看这篇在前/后示例中解释 Symfony DI 新闻的帖子。
2. The Controller
2. 控制器
namespace App\Controller;
final class SomeController
{
/**
* @var string
*/
private $environment;
public function __construct(string $environment)
{
$this->environment = $environment;
}
public function someAction()
{
$this->environment...
// any operations you need
}
}
Why to avoid passing Container in Controller?
为什么要避免在控制器中传递容器?
The most important thing in the code is consistency.
代码中最重要的是一致性。
If you prefer static and service locators (= service you can pass anywhere to get any other service), use it.
If you prefer constructor injection, tree dependency graph (!= circular dependencies), use it.
如果您更喜欢静态和服务定位器(= 您可以通过任何地方获取任何其他服务的服务),请使用它。
如果您更喜欢构造函数注入、树依赖图(!= 循环依赖),请使用它。
Mixing this concept might be ok for you, if you know why you used them that way. But here comes to play The Broken Window Theory (nicely described version by Coding Horror). Anyone coming to the code will more likely pick the version that is not intended to use that way.
混合这个概念对你来说可能没问题,如果你知道你为什么这样使用它们。但是这里来玩破窗理论(Coding Horror 很好地描述了版本)。任何使用代码的人都更有可能选择不打算以这种方式使用的版本。
Ambiguity in the code is the first invitation to legacy code
代码中的歧义是遗留代码的第一个邀请
I've mentored teams of many applications, that started with simple $this->containerin the code and after couple of years ended up calling me for help, how to rewrite or refactor whole static hell.
我指导过许多应用程序的团队,从简单$this->container的代码开始,几年后最终打电话给我寻求帮助,如何重写或重构整个静态地狱。
回答by Martin Kozibratka
From Symfony 4.1 inside Service
从 Symfony 4.1 内部服务
class MyService
{
private $params;
public function __construct(ParameterBagInterface $params)
{
$this->params = $params;
}
public function check($e)
{
if($this->params->get("kernel.environment") === "dev")
{
return true;
}
}
}
回答by Vincent Decaux
In Symfony 4 and higher, you can use simply :
在 Symfony 4 及更高版本中,您可以简单地使用:
if ($this->getParameter('kernel.environment') === 'dev') {
// ...
}
回答by Niket Pathak
For Symfony 4.x and above
对于 Symfony 4.x 及更高版本
If you are using .envto store your environment variables, you can access them in any controllerby simply using $_ENV['name-of-variable']
如果您使用.env来存储环境变量,则只需使用即可在任何控制器中访问它们$_ENV['name-of-variable']
For a default installation, there is a $_ENV["APP_ENV"]variable available, which will tell you if you are in dev mode or not.
对于默认安装,有一个$_ENV["APP_ENV"]变量可用,它会告诉您是否处于开发模式。
Use print_r($_ENV);to see all the available environment variables.
使用print_r($_ENV);看到所有可用的环境变量。
[ps - This also works for Symfony 3.4]
[ps - 这也适用于 Symfony 3.4]
Reference- https://symfony.com/doc/4.3/components/dotenv.html

