duanjing1023 2014-07-03 18:54
浏览 43

PHP自动连线依赖

I'm trying to build a dependency injection container which could auto-wire in dependencies using type hints. The problem arises when dependencies have their own dependencies. In other words I want my dependency container to be able to handle unlimited nested dependencies.

For example auto wiring this class would be easy:

class Bar
{
    public function __construct(Foobar $foobar)
    {
        $this->foobar = $foobar;
    }

}

class foo
{
    public function __construct(Bar $bar)
    {
        $this->bar = $bar;
    }
}

Now if bar also has a dependency i have to somehow inject foobar to bar and only then bar to foo.

class foobar
{

}

class Bar
{
    public function __construct(Foobar $foobar)
    {
        $this->foobar = $foobar;
    }

}


class foo
{
    public function __construct(Bar $bar)
    {
        $this->bar = $bar;
    }
}
  • 写回答

1条回答 默认 最新

  • douqi2571 2015-03-04 00:16
    关注

    You need two things to achieve this: Recursion and Reflection

    Here is a working example:

    function instantiate($class_name) {
        $reflection = new ReflectionClass($class_name);
        $constructor = $reflection->getConstructor();
    
        // If there is no constructor in class, return object as is
        if(!$constructor) return $reflection->newInstance();
    
        $dependencies = [];
    
        $params = $constructor->getParameters();
        foreach ($params as $param) {
            // Check for type hints in constructor
            $paramType = $param->getClass();
            if($paramType) {
                // If there are type hints, call this very function
                // again (recursion) in order to fetch dependency
                $dependencies[] = instantiate($paramType->name);
            }
        }
    
        // Return object (resp. dependency if in recursion loop)
        // while also passing required constructor parameters
        return $reflection->newInstanceArgs($dependencies);
    }
    
    $foo = instantiate('foo');
    

    If you print_r($foo) you'll then see that the object 'foo' contains its dependencies.

    foo Object
    (
        [bar] => Bar Object
            (
                [foobar] => foobar Object
                    (
                    )
    
            )
    
    )
    
    评论

报告相同问题?

悬赏问题

  • ¥15 centos7.9 IPv6端口telnet和端口监控问题
  • ¥120 计算机网络的新校区组网设计
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 海浪数据 南海地区海况数据,波浪数据
  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等
  • ¥15 matlab 用yalmip搭建模型,cplex求解,线性化处理的方法
  • ¥15 qt6.6.3 基于百度云的语音识别 不会改
  • ¥15 关于#目标检测#的问题:大概就是类似后台自动检测某下架商品的库存,在他监测到该商品上架并且可以购买的瞬间点击立即购买下单