从php构造函数获取构造参数依赖

Wil*_*ilt 3 php parameters constructor dependency-injection constructor-injection

使用php ReflectionClass我可以找到我必须在类构造函数中注入哪些参数来创建新实例.

$class = new ReflectionClass($this->someClass);
$constructor = $class->getConstructor();
$parameters = $constructor->getParameters();
Run Code Online (Sandbox Code Playgroud)

是否还有一种方法可以获得这些参数的依赖关系.所以如果构造函数someClass看起来像这样:

public function __construct(Dependency $dependency){
    $this->dependency = $dependency;
}
Run Code Online (Sandbox Code Playgroud)

我能以某种方式从构造函数中获取类Dependency吗?

chr*_*guy 5

ReflectionMethod::getParameters返回一个ReflectionParameter对象数组.ReflectionParameters有一个调用的方法getClass,它将返回有关param的typehint的信息.

例:

<?php
interface Y { }

class X
{
    public function __construct(Y $x, $y=null)
    {

    }
}

$ref = new \ReflectionClass('X');

$c = $ref->getConstructor();
foreach ($c->getParameters() as $p) {
    var_dump($p->getClass());
}
Run Code Online (Sandbox Code Playgroud)

输出:

class ReflectionClass#5 (1) {
  public $name =>
  string(1) "Y"
}
NULL
Run Code Online (Sandbox Code Playgroud)

Silex ControllerResolver有一个非常好的例子,说明如何使用它:

<?php
// $params is an array of ReflectionParameter instances
protected function doGetArguments(Request $request, $controller, array $parameters)
{
    foreach ($parameters as $param) {
        // check to see if there's a class and if there is, see if the app property
        // is the same type. If so, set the attribute on the request
        if ($param->getClass() && $param->getClass()->isInstance($this->app)) {
            $request->attributes->set($param->getName(), $this->app);

            break;
        }
    }

    return parent::doGetArguments($request, $controller, $parameters);
}
Run Code Online (Sandbox Code Playgroud)