在phalcon在控制器中获取以下数据:
post数据是通过$this->request->getPost()
来获取的,查看源码可以看到获取单个值时如果设置了过滤参数就会进行过滤,但是获取全部值时(即不传第一个参数$name
)是不进行过滤,直接返回的($_POST
)。
request数据是通过$this->request->get()
来获取的,过滤机制同上面一样。
json数据是通过$this->request->getJsonRawBody()
来获取的,通过传参(true or false)来返回数组 or 对象。而$this->request->getJsonRawBody()
其实是通过request->getRawBody()
来获取数据并用json_decode解码的。而request->getRawBody()
是通过file_get_contents("php://input")
来获取数据的。这期间也没有过滤。
所以我们可以类似get()那样封装一下,使我们更便捷的获取参数。
打开common/BaseController.php
<?php
/**
* @desc 控制器基类
* @author zhaoyang
* @date 2018年5月8日 下午10:37:37
*/
namespace Common;
use Phalcon\Mvc\Controller;
class BaseController extends Controller {
/**
* @desc 获取get参数
* @param string $name 参数名
* @param string|array $filter 过滤类型,支持string、trim、absint、int、email、float、int!、float!、alphanum、striptags、lower、upper、url、special_chars
* 当为false时,不使用默认过滤,当为字符串例如'string,trim'时采用参数过滤 ,当为数组例如['string','trim']时采用参数+默认过滤,当为null等其他值时时采用默认过滤
* @param mixed $defaultValue 默认值
* @param bool $noRecursive 不递归过滤(即$data不作为数组循环过滤)
* @return mixed
* @author zhaoyang
* @date 2018年5月8日 下午10:38:50
*/
final protected function get(string $name = null, $filter = null, $defaultValue = null, bool $noRecursive = false) {
$data = array_merge($this->request->getQuery(), $this->dispatcher->getParams());
unset($data['_url']);
return $this->sanitize($data, $name, $filter, $defaultValue, $noRecursive);
}
/**
* @desc 获取post参数
* @param string $name 参数名
* @param string|array $filter 过滤类型,支持string、trim、absint、int、email、float、int!、float!、alphanum、striptags、lower、upper、url、special_chars
* 当为false时,不使用默认过滤,当为字符串'string,trim'时采用参数过滤 ,当为数组['string','trim']时采用参数+默认过滤,当为null等其他值时时采用默认过滤
* @param mixed $defaultValue 默认值
* @param bool $noRecursive 不递归过滤(即$data不作为数组循环过滤)
* @return mixed
* @author zhaoyang
* @date 2018年5月9日 下午8:40:27
*/
final protected function post(string $name = null, $filter = null, $defaultValue = null, bool $noRecursive = false) {
$data = $this->request->getPost();
return $this->sanitize($data, $name, $filter, $defaultValue, $noRecursive);
}
/**
* @desc 获取post或者get参数
* @param string $name 参数名
* @param string|array $filter 过滤类型,支持string、trim、absint、int、email、float、int!、float!、alphanum、striptags、lower、upper、url、special_chars
* 当为false时,不使用默认过滤,当为字符串例如'string,trim'时采用参数过滤 ,当为数组例如['string','trim']时采用参数+默认过滤,当为null等其他值时时采用默认过滤
* @param mixed $defaultValue 默认值
* @param bool $noRecursive 不递归过滤(即$data不作为数组循环过滤)
* @return mixed
* @author zhaoyang
* @date 2018年5月9日 下午9:41:49
*/
final protected function request