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

后端 未结 4 818
暖寄归人
暖寄归人 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:00

    Besides all disadvantages explained by others (no control over used services, run time compilation, missing dependencies, etc.)

    There is one main reason, which breaks the main advantage of using DIC - Dependencies replacement.

    If service is defined in library, you wont be able to replace it dependencies with local ones filling your needs.

    Only this reason is strong enough, to not inject whole DIC. You just break whole idea of replacing dependencies since they are HARDCODED! in service;)

    BTW. Don't forget to require interfaces in service constructor instead of specific classes as much as you can - again nice dependencies replacement.

    EDIT: Dependencies replacement example

    Service definition in some vendor:

    
        
    
    

    Replacement in your app:

    
         
    
    

    This allows you to replace vendor logic with your customized one, but don't forget to implement required class interface. With hardcoded dependencies you're not able to replace dependency in one place.

    You can also override vendor_dependency service, but this will replace it in all places not only in vendor_service.

提交回复
热议问题