When using dev mode with a Symfony2.x application, 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 dev mode or not. In that way one can set the behavior of the controller depending by the mode.
Any idea?
Here is 2017 and Symfony 3.3+ version using Constructor Injection.
Instead of passing you whole application (= container), you could pass only the parameter you need:
1. Service config
If you don't understand this syntax, check this post explaining Symfony DI news in before/after examples.
2. The Controller
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.
Ambiguity in the code is the first invitation to legacy code
I've mentored teams of many applications, that started with simple
$this->container
in the code and after couple of years ended up calling me for help, how to rewrite or refactor whole static hell.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
isDebug
method return:As noted in the documentation (emphasis is mine),
As of Symfony 2.5 it could be done as:
Directly asking Kernel of it's environment looks nicer than searching for parameter.
To get the current environment in a
Controller
you can use:So you just put that in an
if()
statement to check if it equals todev
.