ThinkPHP 中间件
ThinkPHP 中间件
中间件主要用于拦截或过滤应用的HTTP请求,并进行必要的业务处理,在TP中主要分为:路由中间件,控制器中间件,全局中间件,模块中间件等。但其中需要注意的点是中间件handle方法的返回值必须是一个Response对象,在某些需求下,可以使用handle方法的第三个参数传入额外的参数。当然也可以给中间件起别名(路由中间件和控制器中间件会用的到)。
下面我以跨域中间件为例
定义中间件
定义CrossDomain.php
<?php
namespace app\http\middleware;
use app\common\exception\ParamException;
use think\facade\Config;
use think\Request;
class CrossDomain
{
/**
* @param Request $request
* @param \Closure $next
* @return mixed|\think\Response
* @throws ParamException
*/
public function handle(Request $request, \Closure $next)
{
$origin = $request->header('origin');
$origin = $origin ? $origin : $request->domain();
$whiteList = Config::get('cross_domain.whiteList',[]);
if ( ! in_array($origin, $whiteList) ) {
throw new ParamException(['errMsg'=>'跨域请求不在白名单中']);
}
header('Access-Control-Allow-Origin:'.$origin);
header('Access-Control-Max-Age:3600');
header('Access-Control-Allow-Methods:GET, POST, OPTIONS');
header('Access-Control-Allow-Headers:X-Requested-With, Content-Type, Accept, Origin, Authorization, X-TOKEN');
if (strtoupper($request->method()) == "OPTIONS") {
return response()->header('Content-Length',0);
}
return $next($request);
}
}
注册中间件
中间件的注册应该使用完整的类名,如果没有指定命名空间则使用app\http\middleware
作为命名空间,跨域中间件属于全局中间件,故在项目应用目录下建立middleware.php
文件进行注册。
return [
\app\http\middleware\CrossDomain::class,
];
路由中间件,控制器中间件和模块中间件在此就不解释了,具体的可以查看官方手册。
本作品采用《CC 协议》,转载必须注明作者和本文链接