(學習筆記)laravel 中間件
laravel的請求在進入邏輯處理之前會通過http中間件進行處理。
也就是說http請求的邏輯是這樣的:
建立中間件
首先,通過Artisan命令建立一個中間件。
php artisan make:middleware [中間件名稱]
例如我創建一個叫做 TestMiddleware的中間件。
php artisan make:middleware TestMiddleware

這樣我們就會在app/http/middleware目錄下看到我們在建立的中間件

注冊中間件
中間件可以是針對route的也可以是針對所有http請求的。
在注冊中間件時這兩種有一定不同。
針對都有http請求
如果中間件在每一個HTTP請求期間都被執行,只需要將相應的中間件類設置到 app/Http/Kernel.php 的數組屬性 $middleware 中即可。
如下:
protected $middleware = [
//這是自帶的例子
\Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
//這是我注冊的中間件
\App\Http\Middleware\TestMiddleware::class,
];
針對特定route
對於針對特定route的中間件。
app/Http/Kernel.php 類的 $routeMiddleware 屬性包含了 Laravel 內置的入口中間件,在其中添加你自己的中間件只需要將其追加到后面並為其分配一個簡寫的key:
protected $routeMiddleware = [
//這是自帶的例子
'auth' => \Illuminate\Auth\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
'can' => \Illuminate\Auth\Middleware\Authorize::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
//這是我注冊的中間件
'test' => \App\Http\Middleware\TestMiddleware::class,
];
在注冊完中間件后就要開始綁定中間件到route。
綁定route有兩種方法。
第一種是通過數組分配
Route::get('/', ['middleware' => ['first', 'second'], function () {
//
}]);
第二種是通過方法鏈來分配
Route::get('/', function () {
//
})->middleware(['first', 'second']);
同時,也可以在Controller中調用中間件,就是在Controller的構造方法中調用:
//Controller的構造方法
public function __construct()
{
//調用中間件
$this->middleware('test');
}
這樣我們就能使用中間件了
中間件代碼分析
中間件可以實現啊很多功能,例如權限驗證,訪問記錄,重定向等等。
具體干什么看自己想法。
中間件在請求階段會調用自己的handle()方法
同時中間件也可以在響應階段使用,這時,會掉用它的terminate()方法。
所以,當需要在響應發出后使用中間件只需要重寫terminate()方法即可。
<?php
namespace App\Http\Middleware;
use Closure;
class TestMiddleware
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
return $next($request);
}
public function terminate($request, $response)
{
//這里是響應后調用的方法
}
}
handle()方法
handle()方法有兩個參數
$request --->請求信息,里面包含了輸入,URL,上傳文件等等信息。
$next --->閉包函數。我的理解是將接下來需要執行的邏輯裝載到了其中。
返回值:
通過上文對參數的描述可以了解到:
當我們在中間件中return $next($request);時,相當與把請求傳入接下來的邏輯中。
同時,中間件也可以返回重定向,不運行之前的邏輯。
例如,希望將頁面重定向到'/welcome'的頁面return redirect('welcome').
注意,這里是重定向到"/welcome"這個地址的route而不是"welcome"這個頁面(view)。
terminate()方法
參數
$request --->請求信息,里面包含了輸入,URL,上傳文件等等信息。
$response -->響應消息,包含了邏輯處理完成后傳出到的響應消息。
因為terminate()方法只是在響應后進行一些處理所以沒有返回值。
