一,官方的文件:
參考地址:
https://docs.golaravel.com/docs/middleware
二,演示:
功能:一箇中介軟體負責驗證使用者是否已登入,
傳遞引數的作用是:在已登入基礎是否驗證真人身份核驗,值為1時要核驗,其他情況可以不用
1, 為中介軟體註冊一個別名:
bootstrap/app.php
->withMiddleware(function (Middleware $middleware) {
//為中介軟體註冊別名
$middleware->alias([
'check' => Check::class
]);
//應用中介軟體
$middleware->append(Sign::class);
})
2,在routes/api.php中傳遞引數:
//評論功能
Route::controller(CommentController::class)->group(function () {
Route::post('/comment/list', 'list')->middleware('check:1');
Route::post('/comment/detail', 'detail')->middleware([Check::class]);
});
3,在中介軟體中接收引數
class Check
{
/**
* Handle an incoming request.
*
* @param \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response) $next
*/
public function handle(Request $request, Closure $next, $isNeedAuth='0'): Response
{
//如果$isNeedAuth值為1,則需要驗證使用者是否已真人核驗
if ($isNeedAuth == 1) {
echo "isNeedAuth:值為1<br/>";
} else {
echo "isNeedAuth:值為0<br/>";
}
}
}