簡(jiǎn)介
Laravel 中間件提供了一種方便的機(jī)制來(lái)過(guò)濾進(jìn)入應(yīng)用的 HTTP 請(qǐng)求, 如
ValidatePostSize
用來(lái)驗(yàn)證POST
請(qǐng)求體大小、ThrottleRequests
用于限制請(qǐng)求頻率等。
那Laravel的中間件是怎樣工作的呢?
啟動(dòng)流程
再說(shuō)Laravel
中間件前侥加,我們先來(lái)理一理laravel
的啟動(dòng)流程
首先,入口文件index.php
加載了autoload
和引導(dǎo)文件bootstrap
require __DIR__.'/../bootstrap/autoload.php';
$app = require_once __DIR__.'/../bootstrap/app.php';
并在引導(dǎo)文件bootstrap/app.php
中初始化了Application
實(shí)例
$app = new Illuminate\Foundation\Application(
realpath(__DIR__.'/../')
);
我們先跳過(guò)如何初始化Application(后面會(huì)有簡(jiǎn)單介紹)磺平,再回到入口文件(index.php)中力麸,通過(guò)從Application
實(shí)例$app
中獲取Http Kernel
對(duì)象來(lái)執(zhí)行handle
方法,換取response
炉奴。
$kernel = $app->make(Illuminate\Contracts\Http\Kernel::class);
$response = $kernel->handle(
$request = Illuminate\Http\Request::capture()
);
$response->send();
$kernel->terminate($request, $response);
換取響應(yīng)后逼庞,把響應(yīng)內(nèi)容返回給Client
,并執(zhí)行后續(xù)操作(terminate瞻赶,如關(guān)閉session等)赛糟。
實(shí)例化Application
:
Laravel的容器并不是我這次說(shuō)的重點(diǎn),這里簡(jiǎn)單介紹下
在初始化Application
(啟動(dòng)容器)時(shí)砸逊,Laravel
主要做了三件事情
- 注冊(cè)基礎(chǔ)綁定
- 注冊(cè)基礎(chǔ)服務(wù)提供者
- 注冊(cè)容器核心別名
注冊(cè)完成以后璧南,我們就能直接從容器中獲取需要的對(duì)象(如Illuminate\\Contracts\\Http\\Kernel
),即使它是一個(gè)Interface
痹兜。
獲取Illuminate\Contracts\Http\Kernel類時(shí)穆咐,我們得到的真正實(shí)例是 App\Http\Kernel
// bootstrap/app.php
$app->singleton(
Illuminate\Contracts\Http\Kernel::class,
App\Http\Kernel::class
);
Laravel容器請(qǐng)參考
Handle
從容器中獲得Http Kernel
對(duì)象后颤诀,Laravel
通過(guò)執(zhí)行kernel->handle
來(lái)?yè)Q取response
對(duì)象字旭。
//Illuminate\Foundation\Http\Kernel.php
public function handle($request)
{
$request->enableHttpMethodParameterOverride();
$response = $this->sendRequestThroughRouter($request);
//......
}
enableHttpMethodParameterOverride
方法開(kāi)啟方法參數(shù)覆蓋,即可以在POST
請(qǐng)求中添加_method
參數(shù)來(lái)偽造HTTP
方法(如post中添加_method=DELETE來(lái)構(gòu)造HTTP DELETE
請(qǐng)求)崖叫。
然后Laravel
把請(qǐng)求對(duì)象(request
)通過(guò)管道流操作遗淳。
protected function sendRequestThroughRouter($request)
{
return (new Pipeline($this->app))
->send($request)
->through($this->app->shouldSkipMiddleware() ? [] : $this->middleware)
->then($this->dispatchToRouter());
}
/**
* Get the route dispatcher callback.
*
* @return \Closure
*/
protected function dispatchToRouter()
{
return function ($request) {
$this->app->instance('request', $request);
return $this->router->dispatch($request);
};
}
Pipeline
是laravel的管道操作類。在這個(gè)方法中心傀,我的理解是:發(fā)送一個(gè)$request
對(duì)象通過(guò)middleware
中間件數(shù)組屈暗,最后在執(zhí)行dispatchToRouter
方法。注意脂男,這里的中間件只是全局中間件养叛。即首先讓Request
通過(guò)全局中間件,然后在路由轉(zhuǎn)發(fā)中($this->dispatchToRouter()
)宰翅,再通過(guò)路由中間件
及中間件group
弃甥。
所以,到這里為止汁讼,Laravel
的請(qǐng)求交給了Pipeline
管理淆攻,讓我們來(lái)看看這個(gè)Pipeline
究竟是怎樣處理的。
//Illuminate\Pipeline\Pipeline.php
public function then(Closure $destination)
{
$pipeline = array_reduce(
array_reverse($this->pipes), $this->carry(), $this->prepareDestination($destination)
);
return $pipeline($this->passable);
}
protected function prepareDestination(Closure $destination)
{
return function ($passable) use ($destination) {
return $destination($passable);
};
}
protected function carry()
{
return function ($stack, $pipe) {
return function ($passable) use ($stack, $pipe) {
if ($pipe instanceof Closure) {
return $pipe($passable, $stack);
} elseif (! is_object($pipe)) {
list($name, $parameters) = $this->parsePipeString($pipe);
$pipe = $this->getContainer()->make($name);
$parameters = array_merge([$passable, $stack], $parameters);
} else {
$parameters = [$passable, $stack];
}
return $pipe->{$this->method}(...$parameters);
};
};
}
我們來(lái)看看最重要的then
方法嘿架, 在這方法中$destination
表示通過(guò)該管道最后要執(zhí)行的Closure
(即上述的dispatchToRouter
方法)瓶珊。passable
表示被通過(guò)管道的對(duì)象Request
。
php
內(nèi)置方法array_reduce
把所有要通過(guò)的中間件($this->pipes
)都通過(guò)carry
方法($this->pipes
不為空時(shí))并壓縮為一個(gè)Closure
耸彪。最后在執(zhí)行prepareDestination
伞芹。
array_reduce($pipes, callback($stack, $pipe), $destination), 當(dāng)pipes為空時(shí)蝉娜,直接執(zhí)行destination丑瞧,否則將所有
$pipes
壓縮為一個(gè)Closure
,最后在執(zhí)行destination
柑土。
列如我有兩個(gè)中間件
Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
App\Http\Middleware\AllowOrigin::class,//自定義中間件
將這兩個(gè)中間件通過(guò)array_reduce
方法時(shí),返回壓縮后的Closure
如:
該Closure
共有三個(gè)層, 前面兩個(gè)為兩個(gè)中間件绊汹,后面?zhèn)€位最后要執(zhí)行的Closure
(即上述的dispatchToRouter
方法)稽屏。
//中間件handle
public function handle($request, Closure $next)
{
}
在第一個(gè)通過(guò)的中間件(此處是CheckForMaintenanceMode
)handle
方法中,dump($next)
如下
在第二個(gè)通過(guò)的中間件(共兩個(gè)西乖,此處是AllowOrigin
)handle
方法中狐榔,dump($next)
如下
由此可知,中間件在執(zhí)行$next($request)
時(shí)获雕,表示該中間件已正常通過(guò)薄腻,并期待繼續(xù)執(zhí)行下一個(gè)中間件。直到所有中間件都執(zhí)行完畢届案,最后在執(zhí)行最后的destination
(即上述的dispatchToRouter
方法)
以上是Laravel
在通過(guò)全局中間件時(shí)的大致流程庵楷,通過(guò)中間件group和路由中間件
也是一樣的, 都是采用管道流操作楣颠,詳情可翻閱源碼
Illuminate\Routing\Router->runRouteWithinStack