Laravel實(shí)現(xiàn)構(gòu)造函數(shù)自動(dòng)依賴(lài)注入的方法
本文實(shí)例講述了Laravel實(shí)現(xiàn)構(gòu)造函數(shù)自動(dòng)依賴(lài)注入的方法。分享給大家供大家參考,具體如下:
在Laravel的構(gòu)造函數(shù)中可以實(shí)現(xiàn)自動(dòng)依賴(lài)注入,而不需要實(shí)例化之前先實(shí)例化需要的類(lèi),如代碼所示:
<?php
namespace Lio\Http\Controllers\Forum;
use Lio\Forum\Replies\ReplyRepository;
use Lio\Forum\Threads\ThreadCreator;
use Lio\Forum\Threads\ThreadCreatorListener;
use Lio\Forum\Threads\ThreadDeleterListener;
use Lio\Forum\Threads\ThreadForm;
use Lio\Forum\Threads\ThreadRepository;
use Lio\Forum\Threads\ThreadUpdaterListener;
use Lio\Http\Controllers\Controller;
use Lio\Tags\TagRepository;
class ForumThreadsController extends Controller implements ThreadCreatorListener, ThreadUpdaterListener, ThreadDeleterListener
{
protected $threads;
protected $tags;
protected $currentSection;
protected $threadCreator;
public function __construct(
ThreadRepository $threads,
ReplyRepository $replies,
TagRepository $tags,
ThreadCreator $threadCreator
) {
$this->threads = $threads;
$this->tags = $tags;
$this->threadCreator = $threadCreator;
$this->replies = $replies;
}
}
注意構(gòu)造函數(shù)中的幾個(gè)類(lèi)型約束,其實(shí)并沒(méi)有地方實(shí)例化這個(gè)Controller并把這幾個(gè)類(lèi)型的參數(shù)傳進(jìn)去,Laravel會(huì)自動(dòng)檢測(cè)類(lèi)的構(gòu)造函數(shù)中的類(lèi)型約束參數(shù),并自動(dòng)識(shí)別是否初始化并傳入。
源碼vendor/illuminate/container/Container.php中的build方法:
$constructor = $reflector->getConstructor(); dump($constructor);
這里會(huì)解析類(lèi)的構(gòu)造函數(shù),在這里打印看:

它會(huì)找出構(gòu)造函數(shù)的參數(shù),再看完整的build方法進(jìn)行的操作:
public function build($concrete, array $parameters = [])
{
// If the concrete type is actually a Closure, we will just execute it and
// hand back the results of the functions, which allows functions to be
// used as resolvers for more fine-tuned resolution of these objects.
if ($concrete instanceof Closure) {
return $concrete($this, $parameters);
}
$reflector = new ReflectionClass($concrete);
// If the type is not instantiable, the developer is attempting to resolve
// an abstract type such as an Interface of Abstract Class and there is
// no binding registered for the abstractions so we need to bail out.
if (! $reflector->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);
}
具體從容器中獲取實(shí)例的方法:
protected function resolveClass(ReflectionParameter $parameter)
{
try {
return $this->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;
}
}
框架底層通過(guò)Reflection反射為開(kāi)發(fā)節(jié)省了很多細(xì)節(jié),實(shí)現(xiàn)了自動(dòng)依賴(lài)注入。這里不做繼續(xù)深入研究了。
寫(xiě)了一個(gè)模擬這個(gè)過(guò)程的類(lèi)測(cè)試:
<?php
class kulou
{
//
}
class junjun
{
//
}
class tanteng
{
private $kulou;
private $junjun;
public function __construct(kulou $kulou,junjun $junjun)
{
$this->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;
原理是通過(guò)ReflectionClass類(lèi)解析類(lèi)的構(gòu)造函數(shù),并且取出構(gòu)造函數(shù)的參數(shù),從而判斷依賴(lài)關(guān)系,從容器中取,并自動(dòng)注入。
轉(zhuǎn)自:小談博客 http://www.tantengvip.com/2016/01/laravel-construct-ioc/
更多關(guān)于Laravel相關(guān)內(nèi)容感興趣的讀者可查看本站專(zhuān)題:《Laravel框架入門(mén)與進(jìn)階教程》、《php優(yōu)秀開(kāi)發(fā)框架總結(jié)》、《smarty模板入門(mén)基礎(chǔ)教程》、《php日期與時(shí)間用法總結(jié)》、《php面向?qū)ο蟪绦蛟O(shè)計(jì)入門(mén)教程》、《php字符串(string)用法總結(jié)》、《php+mysql數(shù)據(jù)庫(kù)操作入門(mén)教程》及《php常見(jiàn)數(shù)據(jù)庫(kù)操作技巧匯總》
希望本文所述對(duì)大家基于Laravel框架的PHP程序設(shè)計(jì)有所幫助。
相關(guān)文章
PHP讀書(shū)筆記整理_結(jié)構(gòu)語(yǔ)句詳解
下面小編就為大家?guī)?lái)一篇PHP讀書(shū)筆記整理_結(jié)構(gòu)語(yǔ)句詳解。小編覺(jué)得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2016-07-07
ThinkPHP控制器里javascript代碼不能執(zhí)行的解決方法
這篇文章主要介紹了ThinkPHP控制器里javascript代碼不能執(zhí)行的解決方法,采用ThinkPHP的<literal>標(biāo)簽來(lái)解決javascript標(biāo)簽被解析的問(wèn)題,是非常實(shí)用的技巧,需要的朋友可以參考下2014-11-11
使用PHP+MySql實(shí)現(xiàn)微信投票功能實(shí)例代碼
這篇文章主要介紹了使用PHP+MySql實(shí)現(xiàn)微信投票功能實(shí)例代碼,需要的朋友可以參考下2017-09-09
PHP使用星號(hào)替代用戶(hù)名手機(jī)和郵箱的實(shí)現(xiàn)代碼
這篇文章主要介紹了PHP使用星號(hào)替代用戶(hù)名手機(jī)和郵箱的實(shí)現(xiàn)代碼,需要的朋友可以參考下2018-02-02

