PHP自动连线依赖

时间:2014-07-03 18:54:13

标签: php dependency-injection

我正在尝试构建一个依赖注入容器,它可以使用类型提示自动连接依赖项。当依赖项具有自己的依赖项时,就会出现问题。换句话说,我希望我的依赖容器能够处理无限制的嵌套依赖项。

例如自动接线这个类很简单:

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

}

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

现在如果bar也有依赖关系,我必须以某种方式将foobar注入bar,然后才禁止foo。

class foobar
{

}

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

}


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

1 个答案:

答案 0 :(得分:0)

你需要做两件事:递归和Reflection

这是一个有效的例子:

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');

如果你print_r($ foo),你会看到对象'foo'包含它的依赖。

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

        )

)