中間件主要用於攔截或過濾應用的HTTP請求,並進行必要的業務處理。
定義中間件:可以通過命令行指令快速生成中間件
php think make:middleware Check
這個指令會 application/http/middleware目錄下面生成一個Check中間件。
<?php namespace app\http\middleware; class Check { public function handle($request, \Closure $next) { } }
中間件的入口執行必須是handle方法,而且第一個參數是Request,第二個參數閉包:
1、前置中間件
前置中間件:主要在請求階段實現,例如判斷登錄狀態,以及訪問權限等等。
<?php namespace app\http\middleware; class Before{ public function handle($request, \Closure $next){ // 添加中間件執行代碼 return $next($request); } }
2、后置中間件
后置中間件:主要是在請求之后實現,例如:寫日志、請求分析等等。
<?php namespace app\http\middleware; class After{ public function handle($request, \Closure $next){ $response = $next($request); // 添加中間件執行代碼 return $response; } }
注冊使用中間件:
在tp5.1的配置文件 config/middleware.php中 【可以預先注冊中間件,增加別名標識】 可用於增加別名
return[ 'check' => app\http\middleware\Check:class, 'auth' => app\http\middleware\Auth:class, 'log' => app\http\middleware\Log:class ]
但是這個注冊使用中間,如果定義了中間件的命名空間即可省略注冊:
return [ // 默認中間件命名空間 'default_namespace' => 'app\\http\\middleware\\', ];
使用中間件:
Route::rule('hello/:name','hello')->middleware('Auth');
或者使用完整的路徑:
Route::rule('hello/:name','hello')->middleware(app\http\middleware\Auth::class);
支持使用多個中間件:
Route::rule('hello/:name','hello')->middleware(['Auth', 'Check']);
我的嘗試:
第一:在路由上使用
在middleware目錄新建 Auth.php
<?php namespace app\http\middleware; class Auth{ /** * 中間件攔截 */ public function handle($request, \Closure $next) { // 添加中間件執行代碼 if(2 > 1){ return error('中間件攔截'); } return $next($request); } }
在路由上使用:
Route::get('addons/abc','addons/index/index')->middleware('Auth');
第二:在控制器中使用
在控制器中使用,配置的路由規則為:
Route::get('addons/abc','addons/index/index');
然后在控制器:定義 protected $middleware
代碼示例:
<?php namespace app\addons\controller; use think\Controller; class Index extends Controller{ protected $middleware = [ 'Auth' ]; public function index(){ echo "this is a addons index controller index function"; } public function login(){ echo "abcd"; } public function hello(){ echo "abcd"; } }
這樣使用中間件,意味着在這個控制器下的所有方法都需要Auth中間件的驗證,解決方法:
處理情況:控制器中的某幾個方法,不需要中間件來驗證。
例如:
auth中間件,使用了except,表示出了hello方法外,這個控制器其他的方法都會執行這個中間件
check中間件,使用了only表示只有這個控制器的login方法執行這個中間件
log中間件,沒有使用任何限定參數,表示這個控制器里面所有的方法都會執行log這個中間件
<?php namespace app\addons\controller; use think\Controller; class Index extends Controller{ // auth中間件,使用了except,表示出了hello方法外,這個控制器其他的方法都會執行這個中間件 // check中間件,使用了only表示只有這個控制器的login方法執行這個中間件 // log中間件,沒有使用任何限定參數,表示這個控制器里面所有的方法都會執行log這個中間件 protected $middleware = [ 'auth' => ['except' => ['hello']], 'check' => ['only' => 'login'], 'log' ]; public function index(){ echo "this is a addons index controller index function"; } public function login(){ echo "abcd"; } public function hello(){ echo "abcd"; } }
這就是中間件的一些使用方法。