中間件是什麼?有什麼作用?
中間件主要用於攔截或過濾應用的HTTP請求,並進行必要的業務處理。---tp5.1手冊
也就是說,降低了系統的耦合;【在http請求階段,執行中間件的入口執行方法(handle)--tp5.1】----減少了系統的一些if/else判斷,因此降低了系統的耦合
中間件可以實現什麼功能,例如權限驗證,訪問記錄,重定向等等。-----這些業務的存在降低了耦合
thinkphp5.1 中的中間件說明:
生成中間件:
php think make:middleware Check
複製代碼
這個指令會 application/http/middleware目錄下面生成一個Check中間件。
<?php
namespace app\http\middleware;
class Check{
//第三個參數,可以通過路由賦值傳遞
public function handle($request, \Closure $next, $name)
{
//下面這一句是 給控制器 傳值
$request->hello = 'ThinkPHP';
if ($name == 'think') {
return redirect('index/think');
}
return $next($request);
}
}
複製代碼
中間件的入口執行方法必須是handle方法,而且第一個參數是Request對象,第二個參數是一個閉包
前置中間件/後置中間件
前置中間件:在請求階段實現,如:判斷登錄狀態,訪問權限等等
<?php
namespace app\http\middleware;
class auth{
public function handle($request, \Closure $next)
{
// 添加中間件執行代碼
return $next($request);
}}
複製代碼
後置中間件:請求完成之後實現,如:寫日誌,請求分析等等
<?php
namespace app\http\middleware;
class Log{
public function handle($request, \Closure $next)
{
$response = $next($request);
// 添加中間件執行代碼
return $response;
}}
複製代碼
tp5.1中的配置文件:middleware.php【可以預先註冊中間件,增加別名標識】,如果沒有指定命名空間則默認使用app\http\middleware
return[
'check' => app\http\middleware\Check:class,
'auth' => app\http\middleware\Auth:class,
'log' => app\http\middleware\Log:class
]
複製代碼
中間件的使用:【說明當一個方法裏面有多箇中間件【前置中間件】時,執行順序按照 設置中間件使用的配置 的順序執行,後置中間件的執行一定是在請求完成之後,才執行的,所以肯定是在最後才被執行】
一、在路由定義配置中設置,如:
return [
//下面路由註冊的中間件,給中間件auth傳遞了"ahai",給中間件check傳遞了"token"參數,不寫,則不傳遞參數
Route::rule('hello/:name','hello')->middleware(['auth:ahai','check:token','log']),
Route::rule('index/:name','think')->middleware('auth')
]
複製代碼
二、在控制器中設置,如:
<?php
namespace app\index\controller;
use think\Controller;
class Index extends Controller{
//這裏配置了中間件,同時限制了中間件的生效操作,
//比如下面的auth中間件,使用了except,表示除了hello方法外,這個控制器的其他的方法都會執行中間件,
//check中間件,使用了only表示只有這個控制器的hello方法執行這個中間件
//log中間件,沒有使用任何限定參數,表示這個控制器的所有方法都會執行log這個中間件
protected $middleware = [
'auth' => ['except' => ['hello'] ],
'check' => ['only' => ['hello'] ],
'log'
];
public function index()
{
echo request()->auth;
echo request()->check;
echo request()->log;
}
public function login()
{
echo request()->auth;
echo request()->check;
echo $this->request->log;
}
public function hello()
{
echo $this->request->log;
echo request()->auth;
echo request()->check;
}
}
複製代碼
<?php
namespace app\http\middleware;
class Auth
{
public function handle($request, \Closure $next)
{
$request->auth = 'auth';
return $next($request);
}
}
<?php
namespace app\http\middleware;
class Log
{
public function handle($request, \Closure $next)
{
$request->log = 'hello';
return $next($request);
}
}
<?php
/**
* Created by ahai
* Time: 2018/9/27 0027 上午 10:18
* Email: <[email protected]>
*/
namespace app\http\middleware;
Class Check
{
public function handle($request, \Closure $next)
{
$request->check = 'check';
return $next($request);
}
}