## 中間件
中間件主要用于攔截或過濾應用的請求,并進行必要的業務處理,通常使用在登錄驗證的場景,基于 [PSR-15](https://www.php-fig.org/psr/psr-15/) 標準實現。
## 組件
使用 [composer]([https://www.phpcomposer.com/](https://www.phpcomposer.com/)) 安裝:
~~~
composer require mix/http-server
~~~
## 定義中間件
~~~
<?php
namespace App\Http\Middleware;
use App\Http\Helpers\ResponseHelper;
use Mix\Auth\Authorization;
use Mix\Auth\BearerTokenExtractor;
use Mix\Http\Message\Response;
use Mix\Http\Message\ServerRequest;
use Mix\Http\Server\Middleware\MiddlewareInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\RequestHandlerInterface;
/**
* Class AuthMiddleware
* @package App\Http\Middleware
* @author liu,jian <coder.keda@gmail.com>
*/
class AuthMiddleware implements MiddlewareInterface
{
/**
* @var ServerRequest
*/
public $request;
/**
* @var Response
*/
public $response;
/**
* @var Authorization
*/
public $auth;
/**
* SessionMiddleware constructor.
* @param ServerRequest $request
* @param Response $response
*/
public function __construct(ServerRequest $request, Response $response)
{
$this->request = $request;
$this->response = $response;
$this->auth = context()->get('auth');
}
/**
* Process an incoming server request.
*
* Processes an incoming server request in order to produce a response.
* If unable to produce the response itself, it may delegate to the provided
* request handler to do so.
*/
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
{
// 權限驗證
$tokenExtractor = new BearerTokenExtractor($request);
try {
$payload = $this->auth->getPayload($tokenExtractor);
} catch (\Throwable $e) {
// 中斷執行,返回錯誤信息
$content = ['code' => 100001, 'message' => 'No access'];
$response = ResponseHelper::json($this->response, $content);
return $response;
}
// 把 JWT Payload 放入 Request 的上下文,方便其他位置調用
$context = $this->request->getContext();
$context->payload = $payload;
// 繼續往下執行
return $handler->handle($request);
}
}
~~~
## 注冊中間件
定義的中間件需要在路由規則 `middleware` 字段中注冊:
```
// 路由規則
'rules' => [
// 普通路由
'/' => [[\App\Http\Controllers\IndexController::class, 'index'], 'middleware' => [\App\Http\Middleware\ActionMiddleware::class]],
],
],
```
### 全局中間件
全局中間件是全局有效的:
~~~
// 路由
[
// 名稱
'name' => 'route',
// 類路徑
'class' => \Mix\Route\Router::class,
// 初始化方法
'initMethod' => 'parse',
// 屬性注入
'properties' => [
...
// 全局中間件
'middleware' => [\App\Http\Middleware\GlobalMiddleware::class],
// 路由規則
'rules' => [
...
],
],
],
~~~
### 分組中間件
分組中間件只在該路由分組的規則中有效:
~~~
// 路由
[
// 名稱
'name' => 'route',
// 類路徑
'class' => \Mix\Route\Router::class,
// 初始化方法
'initMethod' => 'parse',
// 屬性注入
'properties' => [
...
// 路由規則
'rules' => [
...
// 分組路由
'/v2' => [
// 分組中間件
'middleware' => [\App\Http\Middleware\GroupMiddleware::class],
// 分組路由規則
'rules' => [
...
],
],
],
],
],
~~~
框架骨架代碼中默認包含了幾個常用中間件:
- [AuthMiddleware.php](https://github.com/mix-php/mix-skeleton/tree/v2.1/app/Api/Middleware/AuthMiddleware.php "AuthMiddleware.php")
- [SessionMiddleware.php](https://github.com/mix-php/mix-skeleton/tree/v2.1/app/Web/Middleware/SessionMiddleware.php "SessionMiddleware.php")
- [CorsMiddleware.php](https://github.com/mix-php/mix-skeleton/tree/v2.1/app/Api/Middleware/CorsMiddleware.php "CorsMiddleware.php")
- 歡迎使用 MixPHP
- 安裝說明
- 全棧安裝
- Phar 開發安裝
- 新手教程
- 命令行常識
- 進程管理
- 熱更新
- 全局變量
- 入門須知
- 命名空間
- 自動加載
- 入口文件
- 增改應用
- 核心功能
- 配置 (manifest.php)
- 協程
- 什么是協程
- 開啟協程
- PHP Stream Hook
- xgo + Channel
- WaitGroup + xdefer
- 連接池
- 協程池
- 定時器
- 依賴注入
- 事件調度
- 命令行
- 簡介
- Application
- 創建命令
- 命令參數
- 打印與顏色
- 守護進程
- 后臺運行
- Web/API 應用
- 簡介
- 服務器
- 路由
- 中間件
- 請求
- 文件上傳
- 響應
- 控制器
- 視圖
- Auth
- Session
- 客戶端
- GuzzleHttp
- 調試與錯誤
- 安全建議
- WebSocket 應用
- 簡介
- 服務器
- 客戶端
- JavaScript
- Swoole
- nginx代理
- 60s無消息斷線
- TCP 應用
- 簡介
- 服務器
- 客戶端
- Telnet
- PHP
- Swoole
- UDP 應用
- 簡介
- 服務器
- 客戶端
- NC
- Swoole
- Sync Invoke 同步調用
- 簡介
- 服務器
- 客戶端
- 公共組件
- 驗證器
- 驗證器定義
- 驗證規則
- 靜態調用
- 日志
- 緩存
- 數據庫
- Database
- ConnectionPool
- Connection
- QueryBuilder
- ExecutedEvent
- Redis
- ConnectionPool
- Connection
- CalledEvent
- 常見問題
- 如何利用CPU多核
- 連接多個數據庫
- 使用主從數據庫
- 如何設置跨域
- form-data 上傳文件失敗
- 輸出大于2M的文件失敗 (xlsx)
- 如何接入EasyWeChat
- 升級指導
- 不兼容修改-001
- 不兼容修改-002
- 不兼容修改-003