合规国际互联网加速 OSASE为企业客户提供高速稳定SD-WAN国际加速解决方案。 广告
[TOC] ## 前言 所有实例中 writeJson 方法 已经修改 ### writeJson ``` //base Controller protected function writeJson($statusCode = 200, $msg = '', $result = []){ parent::writeJson($statusCode,[],$msg); } ``` ## onRequest 方法前置操作 ``` function onRequest(?string $action): ?bool { if (parent::onRequest($action)) { //判断是否登录 if (1/*伪代码*/) { $this->writeJson(Status::CODE_UNAUTHORIZED, '', '登入已过期'); return false; } return true; } return false; } ``` ## afterAction 方法后置操作 ## index ## actionNotFound ## onException 方法报错,统一走此方法 ``` public function index(){ throw new \Exception("error!!!"); $this->writeJson(200,"asd3"); } function onException(\Throwable $throwable): void { //直接给前端响应500并输出系统繁忙 $this->writeJson(500,'系统繁忙,请稍后再试 '); } ``` ## Validate 验证 ### 验证类型 > [参考](https://www.easyswoole.com/Cn/Components/validate.html) ### 不封装 ``` $validate = new Validate(); //验证必须且长度不大于 5 $validate->addColumn('name','姓名')->required()->lengthMax(5); if (!$this->validate($validate)){ return $this->writeJson(400,$validate->getError()->__toString()); } $this->writeJson(200,"success"); ``` ### 封装 > [参考](https://www.easyswoole.com/Cn/Components/validate.html) ``` //curl http://127.0.0.1:9501/sms?phone=123 public function sms(){ $phone = $this->request()->getRequestParam('phone'); $this->writeJson(200,"phone {$phone}"); } public function onRequest(?string $action): ?bool{ $ret = parent::onRequest($action); if($ret === false){ return false; } $v = $this->validateRule($action); if($v){ $ret = $this->validate($v); if($ret == false){ $this->writeJson(400,"{$v->getError()->getField()}@{$v->getError()->getFieldAlias()}:{$v->getError()->getErrorRuleMsg()}"); return false; } } return true; } protected function validateRule(?string $action): ?Validate { $v = new Validate(); switch ($action){ case 'sms':{ $v->addColumn('phone','手机号')->required('不能为空')->length(11,'长度错误'); break; } } return $v; } ```