1.1.1. 中间件


作用:中间件提供了一种方便的机制用于过滤进入应用程序的 HTTP 请求。

定义中间件:

php artisan make:middleware <name>

这个命令会在 app/Http/Middleware 下生成一个 类。可以将中间件想象成一些列 HTTP 请求,必须进过中间件才能访问应用层。

前置 & 后置中间件

中间件执行的前后顺序,取决于中间件本身。 这个是前置执行,注意注释和 $next($request)的位置

<?php

namespace App\Http\Middleware;

use Closure;

class BeforeMiddleware
{
    public function handle($request, Closure $next)
    {
        // 执行一些任务

        return $next($request);
    }
}

后置执行:

<?php

namespace App\Http\Middleware;

use Closure;

class AfterMiddleware
{
    public function handle($request, Closure $next)
    {
        $response = $next($request);

        // 执行一些任务

        return $response;
    }
}

注册中间件

只需要在 app/Http/kernel.php 文件中注册就行。 如:

// 在 App\Http\Kernel 类中...

protected $routeMiddleware = [
    'auth' => \App\Http\Middleware\Authenticate::class,
    'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
    'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
    'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class,
    'can' => \Illuminate\Auth\Middleware\Authorize::class,
    'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
    'signed' => \Illuminate\Routing\Middleware\ValidateSignature::class,
    'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
    'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,
];

然后就可以直接使用:

# 可以分配多个
Route::get('/', function () {
    //
})->middleware('first', 'second');
Copyright © Kagami丶 2019 all right reserved,powered by Gitbook该文件修订时间: 2019-10-20 14:13:32

results matching ""

    No results matching ""