> # 中间件
<br/>
[TOC]
> 中间件会在每个请求之前执行,可以使用request、response对象,通常用来验证权限之类操作。
<br/>
## **一、定义中间件**
每个中间件都有**前置方法before和后置after**方法,并带上了每个请求的requrest,response对象,这两个对象可以参考swoole文档:https://wiki.swoole.com/wiki/page/328.html , 如下定义中间件:
```
<?php
namespace App\Http\middleware;
class Check
{
public function before($request, $response)
{
echo "this is before middleware\n";
}
public function after($request, $response)
{
echo "this is after middleware\n";
}
}
```
<br/>
## **二、控制器中间件**
如下在控制器中配置中间件:
```
class Index extends Controller
{
public $middleware = '\App\Http\middleware\Check'; //控制器中间件
public function index()
{
$this->fetch("tpl/welcome", ["name" => "开发", "id" => $id]);
}
}
```
需要写上中间件的完整命名空间,请求控制器的每一个方法都会先执行Check中间件。
<br/><br/>
## **三、路由中间件**
定义路由的时候加上middleware参数即可定义每个路由单独的中间件,如下 定义:
```
//http.php
<?php
return [
'tell' => ["GET|POST","index/index/tell","\App\Http\middleware\Check"]
];
```