I need to get current app environment in my service.
I found i can get it from kernel, but many people says it is bad idea to inject kernel.
Could someone explain me why actually it's considered as bad practice?
Isn't it better sollution than injecting whole container into my service?
my_app.my_not_so_great_service:
class: AppBundle\Services\AppService
arguments:
- "@kernel"
An article by Richard Miller[0] explains the issue. The gist of it is that depending on the current app environment is a code smell of a poorly designed architecture and will make you depenedent on concrete implementations.
You cannot easily (hot-)swap implementation logic for a different environment, as you will probably code against a bunch of if/switch-statements. Instead, you should use abstractions which can represent different environments.
The application should not be aware of what environment it is running under, it should just be configured a particular way based on its configuration files. Since we want to vary configuration between different environments there are typically different configuration for each of these environments. We choose which of these sets of configuration to load rather than telling the application which environment it is in.
[0] http://richardmiller.co.uk/2013/05/28/symfony2-avoiding-coupling-applications-to-the-environment/
The kernel object contains the whole app, if you need the environment just inject it:
my_app.my_service:
class: AppBundle\Services\MyAppService
arguments:
- '%kernel.environment%'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With