In Symfony2, why is it a bad idea to inject the service container, rather than individual services?

后端 未结 4 821
暖寄归人
暖寄归人 2020-11-30 02:31

I can\'t find the answer to this...

If I inject the service container, like:

// config.yml
my_listener:
   class: MyListener
   arguments: [@service_         


        
4条回答
  •  我在风中等你
    2020-11-30 03:07

    It is not a good idea because you're making your class dependent on the DI. What happens when some day you decide to pull out your class and use it on an entirely different project? Now I'm not talking about Symfony or even PHP, I'm talking generally. So in that case you have to make sure the new project uses the same kind of DI mechanism with the same methods supported or you get exceptions. And what happens if the project does not use DI at all, or uses some cool new DI implementation? You have to go through your whole codebase and change things to support the new DI. In large projects this can be problematic and costly, especially when you're pulling more than just one class.

    It is best to make your classes as independent as possible. This means keeping the DI out of your usual code, something like a 3rd person who decides what goes where, points where the stuff should go, but doesn't go there and do it himself. This is how I understand it.

    Although, as tomazahlin said, I agree that in Symfony projects in rare occasion it helps prevent circular dependencies. That's the only example where I'd use it and I'd make damn sure that's the only option.

提交回复
热议问题