doublel83422 2013-07-03 16:52
浏览 59
已采纳

依赖注入如何知道要传递哪些变量?

I am struggling with the idea of a dependency injection container.

Not sure how to explain but I will try with a few examples:

class foo
{
    public function __construct(\Somenamespace\Bar $bar, $x)
    {

    }
}

How would the DIC know what 'x' would be?

And if we go further down the road and look at the bar class. The DIC can with no problem with reflection create Bar.

namespace \Somenamespace;
class bar
{
    public function __construct(\SomethingElse\Tap $tap, $y)
    {

    }   
}

The bar wants taps and the tap could also be found by the DIC but how does it know about 'y'?

And if we create the tap.

namespace\SomethingElse;
class tap
{
    public function __construct($amountOfTaps)
    {

    }
}

How would the DIC know about the amount of taps or whatever variable?

EDIT:

Same question does for if the hinted type is an interface or an abstract class. How does a DIC figure out what he needs to create?

  • 写回答

2条回答 默认 最新

  • dongyu9667 2013-07-09 09:59
    关注

    That's a good and a valid question.

    Here is one of the possible answers: the container can't know

    public function __construct(\Somenamespace\Bar $bar, $x)
    
    • $bar is an instance of \Somenamespace\Bar, easy
    • $x could be anything... The container can't know for sure what you want.

    So most containers stop here and ask you to explicitly define (e.g. in a configuration file) what dependency should be injected for $x.


    However some containers can try to guess. For example:

    public function __construct($exportService)
    

    The container can assume that the variable name can be the service name, so it will try to inject the dependency named exportService.

    I don't know any PHP container doing that, I'm planning to implement that in the future in PHP-DI.


    The same goes for "interface injection":

    public function __construct(Some\GoodInterface $x)
    

    In Java, the Container can know all classes that are in a project (they are all grouped in a WAR/JAR archive). So the Java container can look for all implementation of the interface.

    If there is only one, it automatically uses it.

    In PHP, with autoloading, the container can't know all the classes of your project. So all in all, it can't guess what implementation to inject.

    So like above, you will have to define which implementation to use manually (configuration file, …)

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥15 请问Lammps做复合材料拉伸模拟,应力应变曲线问题
  • ¥30 python代码,帮调试
  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥100 Jenkins自动化部署—悬赏100元