You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

频繁注入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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 09:59:54