频繁注入Service Container是否属于不良编程实践?
用容器注入替代特定依赖的服务实现方案
我手头维护着好几个相互依赖的服务,要是逐个去注入特定的依赖项实在太繁琐了。思来想去,我决定给每个这类服务直接注入@service_container,这样就能灵活获取需要的依赖了。最终的实现代码如下:
组件类实现
class InternalComponentHelper implements ContainerAwareInterface { use ContainerAwareTrait; public function somefunction(){ // 在这里使用容器获取所需依赖并执行逻辑 } }
服务配置定义
intcomponent_helper: class: AplicacionBaseBundle\DependencyInjection\Helpers\InternalComponentHelper calls: - [setContainer, ["@service_container"]]
内容的提问来源于stack exchange,提问作者Carlos Gonzalez
相关产品推荐
相关产品推荐

