# 1.8 中間件使用
## 1.8.1 簡介
中間件可以在請求開始或結束時提前對請求進行處理,相對于控制器來說,中間件是全局且優先級更高的一種處理請求的方式,也更高級一些。
## 1.8.2 創建一個中間件
中間件可以位于任何命名空間下,并且名稱可以隨意。
一個中間件必須繼承 `\X\Middleware` 類。
一個中間件有且必須有兩個方法,分別是 `handle` 和 `response` ,且一般不允許有其它方法。
`handle` 方法的參數有兩個,第一個是 Event 觸發時的 Event 實例,詳見 http://event.thephpleague.com/ 。第二個是 `\X\Request` 的實例,是請求數據。
`response` 方法的參數也有兩個,第一個和 `handle` 一致,第二個是 `\X\Response` 的實例,是控制器返回的響應的數據。
在中間件中,可以對這些數據進行修改,也可以直接通過 `$this->app` 訪問到 `\X\Application` 的實例,對程序進行初始化,也可以通過 `$this->app->handler` 獲取到 Handler 實例,對請求進行進一步控制。
一個示例的中間件:
```php
<?php
/**
* XPHP - PHP Framework
*
* This project is licensed
* under MIT. Please use it
* under the license and law.
*
* @category Framework
* @package XPHP
* @author Tianle Xu <xtl@xtlsoft.top>
* @license MIT
* @link https://github.com/xtlsoft/XPHP
*
*/
namespace X\Middleware;
class HttpError extends \X\Middleware {
public function handle($event, \X\Request $request){
// Do Nothing...
}
public function response($event, \X\Response $response){
if(substr($response->dump()->status, 0, 1) != 2){
$view = $this->app->container->get("Core.View");
$httpcode = new \X\Handler\Http;
$httpcode = $httpcode->statusMap;
$rslt = $view->render("System/HttpError", [
"status" => $response->dump()->status,
"header" => $response->dump()->header,
"message"=> $httpcode[$response->dump()->status],
"request"=> $this->app->request->getArray()
]);
$response->write($rslt);
}
}
}
```
這個中間件會在HTTP響應代碼不是200時自動調用 `System/HttpError` 的 View,顯示友好錯誤處理界面。
## 1.8.3 注冊中間件
至此為止,雖然我們創建了中間件,但是XPHP框架還并不知道有這個中間件。要使他生效,我們需要修改 `Register.php` 或 `Config.php` (推薦后者),在主函數體中加入一句話:
```php
$App->boot('中間件的類名');
```
然后,XPHP框架就會自動加載并啟用該中間件。
就是這么簡單,學會了吧?