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条)

报告相同问题?

悬赏问题

  • ¥30 求一段fortran代码用IVF编译运行的结果
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 lammps拉伸应力应变曲线分析
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥15 请问Lammps做复合材料拉伸模拟,应力应变曲线问题
  • ¥30 python代码,帮调试,帮帮忙吧
  • ¥15 #MATLAB仿真#车辆换道路径规划