laravel中间件前置/后置的应用场景
一、前置的场景
如下例子,为一个典型的前置的场景。
public function handle($request, Closure $next)
{
if (Auth::guard('admin')->guest() && $request->path() != 'admin/login') {
if ($request->ajax() || $request->wantsJson()) {
return response('Unauthorized.', 401);
} else {
return redirect()->guest('admin/login');
}
}
return $next($request);
}
解析:
如我要把请求提交到admin的后端,首先要经过我定义的admin相关的中间件,意思大致是,若没有登录,但是又访问了不是登录的接口或者页面,则报错给接口或者重定向到对应的页面。若是合法登录了的用户,请求通过。
二、后置的场景
如下例子,为一个后置的场景。
public function handle($request, Closure $next)
{
try {
$response = $next($request);
} catch (Exception $e) {
$response = $this->handleException($request, $e);
} catch (Error $error) {
$e = new FatalThrowableError($error);
$response = $this->handleException($request, $e);
}
$this->debugbar->modifyResponse($request, $response);
return $response;
}
解析:这个例子当请求完,需要把请求的详细信息都详细打印到用户的浏览器。后置场景一般是用作日志记录,请求分析等内容。
网友评论