在项目根目录/application/下新建http文件夹,在http文件夹下新建middleware文件夹,在middleware文件夹下新建Auth.php文件
<?php
namespace app\http\middleware;
class Auth
{
public function handle($request, \Closure $next) {
/*if (preg_match('~micromessenger~i', $request->header('user-agent'))) {
$request->InApp = 'WeChat';
} else if (preg_match('~alipay~i', $request->header('user-agent'))) {
$request->InApp = 'Alipay';
}*/
return $next($request);
}
}在/application/api/下新建middleware.php文件
<?php
return [
app\http\middleware\Auth::class,
];则/application/api/下的所有控制器&方法都会先经过中间件Auth.php;若只想在某一控制器中使用中间件,则注释掉以上代码后,在具体的控制器(class的括号内)中加入以下即可
protected $middleware = ['Auth'];