控制器对象
http的控制器对象都采用了对象池模式进行获取创建对象.
例如:
- 用户A请求
/Index
,经过url解析以及路由转发,定位到了App\HttpController\Index.php
,控制器 - 由于是第一次请求,
new App\HttpController\Index.php
,并将该对象存入到对象池中 - 对象池出列,获取该对象,并进行调用index方法进行处理请求
- 处理完毕,将对象的属性重置为默认值,对象回收对象池
- 用户B请求
/Index
,经过url解析以及路由转发,定位到了App\HttpController\Index.php
,控制器 - 由于是二次请求,对象池直接获取到第一次的对象,不需要new,直接调用 index方法进行处理
对象方法
- “action”
“action”是控制器最终执行的方法,根据路由的匹配不同,从而执行不同的控制器方法,例如默认执行的index
方法,例如访问ip/Index/test
最终解析的test
方法,都可以称作”action”执行方法.action方法可以返回一个字符串,从而让框架再次进行控制器方法调度,例如:
- onRequest
<?php
protected function onRequest(?string $action): ?bool
{
return true;
}
在准备调用控制器方法处理请求时的事件,如果该方法返回false则不继续往下执行.
可用于做控制器基类权限验证等,例如:
function onRequest(?string $action): ?bool
{
if (parent::onRequest($action)) {
//判断是否登录
if (1/*伪代码*/) {
$this->writeJson(Status::CODE_UNAUTHORIZED, '', '登入已过期');
}
}
return false;
}
afterAction
当控制器方法执行结束之后将调用该方法,可自定义数据回收等逻辑index
index是一个抽象方法,代表着继承控制器对象的都需要实现该方法,index 将成为默认的控制器方法.-
该方法可以理解成
默认方法
,类似于index
方法,所以调用完之后也会触发afterAction
,gc
等方法 - onException
当控制器逻辑抛出异常时将调用该方法进行处理异常(框架默认已经处理了异常)
可覆盖该方法,进行自定义的异常处理,例如: - gc
gc 方法将在执行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;
}
}
方法
,afterAction
完之后自动调用
将控制器属性重置为默认值,关闭session
可自行覆盖实现其他的gc回收逻辑.
- request
request方法调用之后,将返回EasySwoole\Http\Request
对象
该对象附带了用户请求的所有数据,例如:function index()
$request = $this->request();
$request->getMethod();//获取请求方式(post/get/)
$request->getCookieParams();//获取cookie参数
}
更多request相关可查看
- response
response方法将返回EasySwoole\Http\Response
,用于向客户端响应数据,例如: - writeJson
writeJson方法直接封装了设置响应状态码,设置响应头,数组转为json输出.
网页输出:function index()
{
$this->writeJson(200,['xsk'=>'仙士可'],'success');
}
{"code":200,"result":{"xsk":"仙士可"},"msg":"success"}
- json
使用json_decode 解析json字符串 - xml
使用simplexml_load_string解析xml字符串
- sessionDriver
设置session的驱动类,默认为EasySwoole\Http\Session\SessionDriver
- session
返回session的驱动类,进行管理session
- validate
validate方法可直接调用EasySwoole\Validate\Validate
对象的验证,返回验证成功/失败的结果,实现代码: 我们可使用该方法进行验证客户端发送的数据:function index()
{
$validate = new Validate();
$validate->addColumn('name','姓名')->required()->lengthMax(50);
//限制name必填并且不能大于50个字符串
if (!$this->validate($validate)){
$this->writeJson(400, [], $validate->getError()->__toString());
return false;
}
$this->writeJson(200, [], 'success');
}
更多validate 相关可查看验证器