在使用laravel的时候,可以看到大量地使用了依赖注入。比如控制器中的HttpRequest对象,各种Model的实现类等等。这种实现方式的好处在于不需要再方法中频繁地new某些实例,实现模块的解耦。
依赖注入使用PHP反射API实现
反射机制被多种语言使用,用来获取类、实例对象、方法等语言构件信息,通过反射API函数可以动态进行操作。以下编写了简单的例子来说明。我们需要调用App::run方法,看看怎么来实现:
<?php
class App
{
public function run(View $view)
{
echo $view->display();
}
}
class View
{
private $content;
public function __construct(string $content)
{
$this->content = $content;
}
public function display() : string
{
return $this->content;
}
}
//$app = new App();
//$app->run(new View("hello!"));
$app = new App();
$reflectorApp = new ReflectionClass($app);
//获取App::run方法的ReflectionMethod对象
$reflectionMethod = $reflectorApp->getMethod("run");
$params = $reflectionMethod->getParameters();
//params是ReflectionParameter对象的数组
$instanceList = [];
foreach ($params as $param) {
$reflector = $param->getClass();
//依赖注入的参数应该由容器来管理,这里仅仅用于展示,就直接new了
if ($reflector->getName() == 'View') {
$instanceList[] = new View('hello!');
}
}
call_user_func_array([$app, "run"], $instanceList);
更多反射API,可参考: