laravel中間件middleware如何使用詳細(xì)講解

什么是中間件

可以簡單地將中間件理解為請(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";
    }
}

以上方法中,路由分組注冊中間件最常用

源碼庫

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容