laravel中间件Middleware原理解析及实例
一、总结
一句话总结:
二、laravel中间件Middleware原理解析
1、身份中间件 实例
legend3/app/Http/Middleware/Home/User.php
这是写的中间件的代码,逻辑就是判断用户是否登录,没登录就退出
1 <?php 2 3 namespace AppHttpMiddlewareHome; 4 5 use Closure; 6 use Auth; 7 8 class User 9 { 10 /** 11 * Handle an incoming request. 12 * 13 * @param IlluminateHttpRequest $request 14 * @param Closure $next 15 * @return mixed 16 */ 17 public function handle($request, Closure $next) 18 { 19 //前端的登录中间件 20 //作用是用Auth::guard('user')->check()来验证用户登录, 21 //如果登录成功就进行下一步 22 //如果没有登录成功就返回到登录页 23 if(!Auth::guard('user')->check()){ 24 return redirect('/login'); 25 } 26 return $next($request); 27 } 28 }
legend3/app/Http/Kernel.php
这里是注册中间件,相当于给中间件取别名,使用的时候可以直接通过别名调用
1 protected $routeMiddleware = [ 2 //fry 3 //后端的登录中间件注册 4 'admin.auth'=>MiddlewareAdminAdmin::class, 5 //前端的登录中间件注册 6 'home.auth'=>MiddlewareHomeUser::class, 7 8 // 9 10 'auth' => AppHttpMiddlewareAuthenticate::class, 11 'auth.basic' => IlluminateAuthMiddlewareAuthenticateWithBasicAuth::class, 12 'bindings' => IlluminateRoutingMiddlewareSubstituteBindings::class, 13 'cache.headers' => IlluminateHttpMiddlewareSetCacheHeaders::class, 14 'can' => IlluminateAuthMiddlewareAuthorize::class, 15 'guest' => AppHttpMiddlewareRedirectIfAuthenticated::class, 16 'signed' => IlluminateRoutingMiddlewareValidateSignature::class, 17 'throttle' => IlluminateRoutingMiddlewareThrottleRequests::class, 18 'verified' => IlluminateAuthMiddlewareEnsureEmailIsVerified::class, 19 ];
在配置文件auth中注册guard
如果使用Auth::guard('user')->check()
中的guard,就需要注册guard
如果只是作为普通中间件使用,不使用guard,就不需要
例如$this->middleware('home.auth')->except(['index','get_video_comment']);
使用
在各个控制器中
class VideoController extends Controller { public function __construct() { //排除'index'方法,进行中间件的验证 $this->middleware('home.auth')->except(['index','get_video_comment']); // $this->middleware('home.auth')->except(['get_video_comment']); } 省略若干代码... }
如果没有登录,就会被被中间件拦截,跳转到登录页面
2、pjax中间件 实例
注册
中间件代码及位置
pjax中间件代码中的逻辑也非常简单,如果不是pjax请求或者是重定向,就不处理这个请求
否则就处理这个请求