Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony 2: why injecting kernel into service is bad idea?

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"
like image 372
fghjkdfghjrghjk Avatar asked Mar 11 '23 04:03

fghjkdfghjrghjk


2 Answers

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/

like image 198
Elias Avatar answered Mar 13 '23 17:03

Elias


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%'
like image 44
lolmx Avatar answered Mar 13 '23 18:03

lolmx