* action
`action`是控制器最終執行的方法,根據路由的匹配不同,從而執行不同的控制器方法,例如默認執行的`index`方法,例如訪問`ip/Index/test`最終解析的`test`方法,都可以稱作`action`執行方法.
action方法可以返回一個字符串,從而讓框架再次進行控制器方法調度,例如:
~~~php
<?php
/**
* Created by PhpStorm.
* User: Tioncico
* Date: 2019/4/11 0011
* Time: 14:40
*/
namespace App\HttpController;
use EasySwoole\EasySwoole\Trigger;
use EasySwoole\Http\AbstractInterface\Controller;
use EasySwoole\Http\Message\Status;
class Index extends Controller
{
function index()
{
$this->writeJson(200, [], 'success');
return '/test';
}
function test()
{
$this->response()->write('this is test');
return '/test2';//當執行完test方法之后,返回/test2,讓框架繼續調度/test2方法
}
function test2()
{
$this->response()->write('this is test2');
return true;
}
}
~~~
返回的字符串將會被`url解析規則`以及`route路由`規則解析,但是需要注意,千萬不能A方法返回B方法,B方法再返回A方法的字符串,否則會出現無限死循環調用
* onRequest
~~~php
protected function onRequest(?string $action): ?bool
{
return true;
}
~~~
在準備調用控制器方法處理請求時的事件,如果該方法返回false則不繼續往下執行.
可用于做控制器基類權限驗證等,例如:
~~~php
function onRequest(?string $action): ?bool
{
if (parent::onRequest($action)) {
//判斷是否登錄
if (1/*偽代碼*/) {
$this->writeJson(Status::CODE_UNAUTHORIZED, '', '登入已過期');
return false;
}
return true;
}
return false;
}
~~~
* afterAction
當控制器方法執行結束之后將調用該方法,可自定義數據回收等邏輯
* index
index是一個抽象方法,代表著繼承控制器對象的都需要實現該方法,index 將成為默認的控制器方法.
* actionNotFound
當請求方法未找到時,自動調用該方法,可自行覆蓋該方法實現自己的邏輯
該方法可以理解成`默認方法`,類似于`index`方法,所以調用完之后也會觸發`afterAction`,`gc`等方法
* onException
當控制器邏輯拋出異常時將調用該方法進行處理異常(框架默認已經處理了異常)
可覆蓋該方法,進行自定義的異常處理,例如:
~~~php
function onException(\Throwable $throwable): void
{
//直接給前端響應500并輸出系統繁忙
$this->response()->withStatus(Status::CODE_INTERNAL_SERVER_ERROR);
$this->response()->write('系統繁忙,請稍后再試 ');
}
~~~
更多控制器異常相關可查看[錯誤與異常攔截](https://www.easyswoole.com/Cn/HttpServer/exception.html)
* gc
~~~php
protected function gc()
{
// TODO: Implement gc() method.
if ($this->session instanceof SessionDriver) {
$this->session->writeClose();
$this->session = null;
}
//恢復默認值
foreach ($this->defaultProperties as $property => $value) {
$this->$property = $value;
}
}
~~~
gc 方法將在執行`方法`,`afterAction`完之后自動調用
將控制器屬性重置為默認值,關閉`session`
可自行覆蓋實現其他的gc回收邏輯.