[TOC]
# 簡介
> Laravel 中間件提供了一種方便的機制來過濾進入應用的 HTTP 請求, 如ValidatePostSize用來驗證POST請求體大小、ThrottleRequests用于限制請求頻率等。
那Laravel的中間件是怎樣工作的呢?
# 啟動流程
再說Laravel中間件前,我們先來理一理laravel的啟動流程
首先,入口文件index.php加載了autoload和引導文件bootstrap
~~~
require __DIR__.'/../bootstrap/autoload.php';
$app = require_once __DIR__.'/../bootstrap/app.php';
~~~
并在引導文件bootstrap/app.php中初始化了Application實例
~~~
$app = new Illuminate\Foundation\Application(
realpath(__DIR__.'/../')
);
~~~
我們先跳過如何初始化Application(后面會有簡單介紹),再回到入口文件(index.php)中,通過從Application實例$app中獲取Http Kernel對象來執行handle方法,換取response。
~~~
$kernel = $app->make(Illuminate\Contracts\Http\Kernel::class);
$response = $kernel->handle(
$request = Illuminate\Http\Request::capture()
);
$response->send();
$kernel->terminate($request, $response);
~~~
換取響應后,把響應內容返回給Client,并執行后續操作(terminate,如關閉session等)。
實例化Application:
Laravel的容器并不是我這次說的重點,這里簡單介紹下
在初始化Application(啟動容器)時,Laravel主要做了三件事情
1. 注冊基礎綁定
2. 注冊基礎服務提供者
3. 注冊容器核心別名
注冊完成以后,我們就能直接從容器中獲取需要的對象(如Illuminate\\Contracts\\Http\\Kernel),即使它是一個Interface。
> 獲取Illuminate\Contracts\Http\Kernel類時,我們得到的真正實例是 App\Http\Kernel
~~~
// bootstrap/app.php
$app->singleton(
Illuminate\Contracts\Http\Kernel::class,
App\Http\Kernel::class
);
~~~
# Handle
從容器中獲得Http Kernel對象后,Laravel通過執行kernel->handle來換取response對象。
~~~
//Illuminate\Foundation\Http\Kernel.php
public function handle($request)
{
$request->enableHttpMethodParameterOverride();
$response = $this->sendRequestThroughRouter($request);
//......
}
~~~
enableHttpMethodParameterOverride方法開啟方法參數覆蓋,即可以在POST請求中添加_method參數來偽造HTTP方法(如post中添加_method=DELETE來構造HTTP DELETE請求)。
然后Laravel把請求對象(request)通過管道流操作
~~~
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的管道操作類。在這個方法中,我的理解是:發送一個$request對象通過middleware中間件數組,最后在執行dispatchToRouter方法。注意,這里的中間件只是全局中間件。即首先讓Request通過全局中間件,然后在路由轉發中($this->dispatchToRouter()),再通過路由中間件及中間件group。
所以,到這里為止,Laravel的請求交給了Pipeline管理,讓我們來看看這個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);
};
};
}
~~~
我們來看看最重要的then方法, 在這方法中$destination表示通過該管道最后要執行的Closure(即上述的dispatchToRouter方法)。passable表示被通過管道的對象Request。
php內置方法array_reduce把所有要通過的中間件($this->pipes)都通過carry方法($this->pipes不為空時)并壓縮為一個Closure。最后在執行prepareDestination。
>array_reduce($pipes, callback($stack, $pipe), $destination), 當pipes為空時,直接執行destination,否則將所有$pipes壓縮為一個Closure,最后在執行destination。
列如我有兩個中間件
~~~
Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
App\Http\Middleware\AllowOrigin::class,//自定義中間件
~~~
將這兩個中間件通過array_reduce方法時,返回壓縮后的Closure如:

該Closure共有三個層, 前面兩個為兩個中間件,后面個位最后要執行的Closure(即上述的dispatchToRouter方法)。
~~~
//中間件handle
public function handle($request, Closure $next)
{
}
~~~
在第一個通過的中間件(此處是CheckForMaintenanceMode)handle方法中,dump($next)如下

在第二個通過的中間件(共兩個,此處是AllowOrigin)handle方法中,dump($next)如下

由此可知,中間件在執行$next($request)時,表示該中間件已正常通過,并期待繼續執行下一個中間件。直到所有中間件都執行完畢,最后在執行最后的destination(即上述的dispatchToRouter方法)
以上是Laravel在通過全局中間件時的大致流程,通過中間件group和路由中間件也是一樣的, 都是采用管道流操作,詳情可翻閱源碼
~~~
Illuminate\Routing\Router->runRouteWithinStack
~~~
- 配置
- composer安裝
- composer用法
- composer版本約束表達
- phpstorm
- sftp文件同步
- php類型約束
- laradock
- 配置文件緩存詳解
- git
- 自定義函數
- 核心概念
- IOC
- 服務提供者
- Facade
- 契約
- 生命周期
- 路由
- 請求
- 命名路由
- 路由分組
- 資源路由
- 控制器路由
- 響應宏
- 響應
- Command
- 創建命令
- 定時任務
- console路由
- 執行用戶自定義的定時任務
- artisan命令
- 中間件
- 創建中間件
- 使用中間件
- 前置和后置
- 詳細介紹
- 訪問次數限制
- 為 VerifyCsrfToken 添加過濾條件
- 單點登錄
- 事件
- 創建
- ORM
- 簡介
- DB類
- 配置
- CURD
- queryScope和setAttribute
- 查看sql執行過程
- 關聯關系
- 一對一
- 一對多
- 多對多
- 遠程關聯
- 多態一對多
- 多態多對多
- 關聯數據庫的調用
- withDefault
- 跨模型更新時間戳
- withCount,withSum ,withAvg, withMax,withMin
- SQL常見操作
- 模型事件
- 模型事件詳解
- 模型事件與 Observer
- deleted 事件未被觸發
- model validation
- ORM/代碼片段
- Repository模式
- 多重where語句
- 中間表類型轉換
- Collection集合
- 新增的一些方法
- 常見用法
- 求和例子
- 機場登機例子
- 計算github活躍度
- 轉化評論格式
- 計算營業額
- 創建lookup數組
- 重新組織出表和字段關系并且字段排序
- 重構循環
- 其他例子
- 其他問題一
- 去重
- 第二個數組按第一個數組的鍵值排序
- 搜索ES
- 安裝
- 表單
- Request
- sessiom
- Response
- Input
- 表單驗證
- 簡介
- Validator
- Request類
- 接口中的表單驗證
- Lumen 中自定義表單驗證返回消息
- redis
- 廣播事件
- 發布訂閱
- 隊列
- 守護進程
- redis隊列的坑
- beanstalkd
- rabbitmq
- redis隊列
- 日志模塊
- 錯誤
- 日志詳解
- 數據填充與遷移
- 生成數據
- 數據填充seed
- migrate
- 常見錯誤
- Blade模板
- 流程控制
- 子視圖
- URL
- 代碼片段
- Carbon時間類
- 一些用法
- 郵件
- 分頁
- 加密解密
- 緩存
- 文件上傳
- 優化
- 隨記
- 嵌套評論
- 判斷字符串是否是合法的 json 字符串
- 單元測試
- 計算出兩個日期的diff
- 自定義一個類文件讓composer加載
- 時間加減
- 對象數組互轉方法
- 用戶停留過久自動退出登錄
- optional 輔助方法
- 文件下載
- Api
- Dingo api
- auth.basic
- api_token
- Jwt-Auth
- passport
- Auth
- Authentication 和 Authorization
- Auth Facade
- 授權策略
- Gates
- composer包
- debug包
- idehelp包
- image處理
- 驗證碼
- jq插件
- 第三方登錄
- 第三方支付
- log顯示包
- 微信包
- xss過濾
- Excel包
- MongoDB
- php操作
- 聚合查詢
- 發送帶附件郵件
- 中文轉拼音包
- clockwork網頁調試
- emoji表情
- symfony組件
- swooletw/laravel-swoole
- 常見問題
- 跨域問題
- Laravel隊列優先級的一個坑
- cache:clear清除緩存問題
- .env無法讀取
- 源碼相關基礎知識
- __set和__get
- 依賴注入、控制反轉和依賴倒置原則
- 控制反轉容器(Ioc Container)
- 深入服務容器
- call_user_func
- compact
- 中間件簡易實現
- array_reduce
- 中間件實現代碼
- Pipeline管道操作
- composer自動加載
- redis延時隊列
- 了解laravel redis隊列
- cli
- 源碼解讀
- Facade分析
- Facade源碼分析
- IOC服務容器
- 中間件原理
- 依賴注入淺析
- 微信
- 微信公眾號
- 常用接收消息
- 6大接收接口
- 常用被動回復消息
- 接口調用憑證
- 自定義菜單
- 新增素材
- 客服消息
- 二維碼
- 微信語音
- LBS定位
- 網頁授權
- JSSDK
- easywechat
- 小程序
- 小程序配置app.json