Laravel实现构造函数自动依赖注入的方法
本篇章节讲解Laravel实现构造函数自动依赖注入的方法。分享给大家供大家参考,具体如下: 在Laravel的构造函数中可以实现自动依赖注入,而不需要实例化之前先实例化需要的类,如代码所示: threads = $threads;
$this->tags = $tags;
$this->threadCreator = $threadCreator;
$this->replies = $replies;
}
}
注意构造函数中的几个类型约束,其实并没有地方实例化这个Controller并把这几个类型的参数传进去,Laravel会自动检测类的构造函数中的类型约束参数,并自动识别是否初始化并传入。 源码vendor/illuminate/container/Container.php中的build方法: getConstructor();
dump($constructor);
这里会解析类的构造函数,在这里打印看: 它会找出构造函数的参数,再看完整的build方法进行的操作: isInstantiable()) {
$message = "Target [$concrete] is not instantiable.";
throw new BindingResolutionContractException($message);
}
$this->buildStack[] = $concrete;
$constructor = $reflector->getConstructor();
// If there are no constructors,that means there are no dependencies then
// we can just resolve the instances of the objects right away,without
// resolving any other types or dependencies out of these containers.
if (is_null($constructor)) {
array_pop($this->buildStack);
return new $concrete;
}
$dependencies = $constructor->getParameters();
// Once we have all the constructor's parameters we can create each of the
// dependency instances and then use the reflection instances to make a
// new instance of this class,injecting the created dependencies in.
$parameters = $this->keyParametersByArgument(
$dependencies,$parameters
);
$instances = $this->getDependencies(
$dependencies,$parameters
);
array_pop($this->buildStack);
return $reflector->newInstanceArgs($instances);
}
具体从容器中获取实例的方法: make($parameter->getClass()->name);
}
// If we can not resolve the class instance,we will check to see if the value
// is optional,and if it is we will return the optional parameter value as
// the value of the dependency,similarly to how we do this with scalars.
catch (BindingResolutionContractException $e) {
if ($parameter->isOptional()) {
return $parameter->getDefaultValue();
}
throw $e;
}
}
框架底层通过Reflection反射为开发节省了很多细节,实现了自动依赖注入。这里不做继续深入研究了。 写了一个模拟这个过程的类测试: kulou = $kulou;
$this->junjun = $junjun;
}
}
//$tanteng = new tanteng(new kulou(),new junjun());
$reflector = new ReflectionClass('tanteng');
$constructor = $reflector->getConstructor();
$dependencies = $constructor->getParameters();
print_r($dependencies);exit;
原理是通过ReflectionClass类解析类的构造函数,并且取出构造函数的参数,从而判断依赖关系,从容器中取,并自动注入。 转自:小谈博客 http://www.tantengvip.com/2016/01/laravel-construct-ioc/ 更多关于Laravel相关内容感兴趣的读者可查看本站专题:《》、《》、《》、《》、《》、《》、《》及《》 希望本文所述对大家基于Laravel框架的PHP程序设计有所帮助。 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |