什么是中間件
可以簡單地將中間件理解為請(qǐng)求與響應(yīng)之間的中間人。用戶發(fā)出一個(gè)路由請(qǐng)求,經(jīng)過中間件的驗(yàn)證或過濾后,才能獲取相應(yīng)的響應(yīng)內(nèi)容。

image
定義中間件
laravel提供了定義中間件的指令,如定義一個(gè)獲取當(dāng)前時(shí)間的中間件
$ php artisan make:middleware GetCurrentTime
自動(dòng)生成了 app/Http/Middleware/GetCurrentTime.php 文件

image
在 handle方法中寫具體的業(yè)務(wù)代碼:
public function handle($request, Closure $next)
{
dump(date('Y-m-d H:i:s', time()));
return $next($request);
}
注冊中間件
定義好的中間件需要進(jìn)行注冊才能使用,注冊的方式有三種:
全局注冊
即所有路由都必須經(jīng)過此中間件
在 app/Http/Kernel.php 中的 $middleware 進(jìn)行注冊:
protected $middleware = [
# ...
\App\Http\Middleware\GetCurrentTime::class,
];
效果如下:

image
全局注冊作用于所有路由,應(yīng)用的場景比較少,畢竟開銷太大
路由注冊
只針對(duì)特定的路由起作用
首先在 app/Http/Kernel.php 的 $routeMiddleware 中注冊自定義的路由
protected $routeMiddleware = [
# ...
'get_current_time' => \App\Http\Middleware\GetCurrentTime::class,
];
然后在 routes/web.php 中將中間件綁定到指定的路由
Route::get('test', 'TestController@index')->name('test')->middleware('get_current_time')
創(chuàng)建TestController:
$ php artisan make:controller TestController

image
瀏覽器訪問:http://local.laravel-study.com/test

image
這種將中間件逐一綁定到路由的方式效率太低了,一般采用路由分組的方式進(jìn)行綁定,格式如下:
Route::group(['middleware' => ['get_current_time']], function () {
Route::get('test', 'TestController@index')->name('test');
});
控制器中注冊
去掉路由中的中間件綁定
Route::get('test', 'TestController@index')->name('test');
修改 app/Http/Controllers/TestController.php 代碼:
class TestController extends Controller
{
public function __construct()
{
// 排除某些方法
// return $this->middleware(['get_current_time'])->except('index');
return $this->middleware(['get_current_time']);
}
public function index()
{
echo "test";
}
}
以上方法中,路由分組注冊中間件最常用