控制器参数验证的需求与痛点
在开发 API 接口时,通常需要在控制器层面对传入的请求参数进行基础的正确性校验。
若仅依赖 Yii 框架自带的验证器功能,目前主要有两种实现路径,但实际效果往往不尽如人意。
第一种是为每个请求单独创建一个 Model 类,在其中定义具体的验证规则并执行验证。这种做法的主要弊端在于,随着接口数量增加,需要编写大量仅用于参数校验的 Model 类,导致代码膨胀。
第二种方式是参考独立验证器的相关文档,利用 $validator->validateValue() 方法直接对变量值进行验证。其缺点在于需要频繁实例化大量的验证器对象,增加了代码复杂度。那么,是否存在一种“一劳永逸”的方案,能够像 Model 中通过 rules 方法那样,灵活定义验证规则并实现快速验证呢?答案是肯定的。
以下是该方案的具体使用方式及预期达到的效果。
namespace frontend\controllers\api;
use yii\web\Controller;
use common\services\app\ParamsValidateService;
class ArticleController extends Controller
{
// 文章列表
public function actionList()
{
$PVS = new ParamsValidateService();
$valid = $PVS->validate(\Yii::$app->request->get(), [
['category_id', 'required'],
['category_id', 'integer'],
['keyword', 'string'],
]);
if (!$valid) {
$this->apiError(1001, $PVS->getErrorSummary(true));
}
//...
}
// 新增文章
public function actionPost()
{
$PVS = new ParamsValidateService();
$valid = $PVS->validate(\Yii::$app->request->get(), [
[['category_id', 'title', 'content'], 'required'],
['category_id', 'integer'],
[['title'], 'string', 'max' => 64],
[['content'], 'string'],
]);
if (!$valid) {
$this->apiError(1001, $PVS->getErrorSummary(true));
}
//...
}
// 文章删除
public function actionDelete()
{
$PVS = new ParamsValidateService();
$valid = $PVS->validate(\Yii::$app->request->get(), [
['article_id', 'required'],
['article_id', 'integer'],
]);
if (!$valid) {
$this->apiError(1001, $PVS->getErrorSummary(true));
}
//...
}
}
具体的代码实现逻辑如下。
首先,需要定义一个专门用于参数验证的模型类。
创建参数验证模型 ParamsValidateModel ,该类需继承自 yii\db\ActiveRecord ,并重写 attributes() 方法。这一设计主要承担以下核心功能:
- 支持从对象外部动态设置参数验证规则。
- 能够从已定义的验证规则中提取出所有可赋值的属性列表。
<?php
namespace common\models\app;
use yii\db\ActiveRecord;
class ParamsValidateModel extends ActiveRecord
{
/**
* @var array 验证规则
*/
private $_rules = [];
private $_attributes = [];
// 设置验证规则
public function setRules($rules)
{
$this->_rules = $rules;
foreach ($rules as $item) {
$this->_attributes = array_unique(array_merge($this->_attributes, (array)$item[0]));
}
}
// 重写获取验证规则
public function rules()
{
return $this->_rules;
}
// 设置可用属性列表
public function attributes()
{
return $this->_attributes;
}
}
接下来,定义参数验证的服务类。
该服务类主要具备以下功能模块:
- 负责接收并设置参数列表以及对应的参数规则列表。
- 调用前述的 参数验证模型 执行实际的验证操作,并将产生的验证错误消息存储起来。
- 通过魔术方法便捷地获取 参数验证模型 中累积的验证错误消息。
<?php
namespace common\services\app;
use common\models\app\ParamsValidateModel;
use yii\base\Component;
/**
* Class ParamsValidateService
* @package common\services\app
* @method array getErrors(\string $attribute)
* @method array getFirstErrors()
* @method array getFirstError(\string $attribute)
* @method array getErrorSummary(\boolean $showAllErrors)
*/
class ParamsValidateService extends Component
{
/**
* @var ParamsValidateModel 模型
*/
private $model = null;
public function init()
{
parent::init();
$this->model = new ParamsValidateModel();
}
/**
* @param array $data 数据项
* @param array $rules 验证规则
* @return bool
*/
public function validate($data, $rules)
{
// 添加验证规则
$this->model->setRules($rules);
// 设置参数
$this->model->load($data, '');
// 进行验证
return $this->model->validate();
}
public function __call($name, $params)
{
if ($this->model->hasMethod($name)) {
return call_user_func_array([$this->model, $name], $params);
} else {
return parent::__call($name, $params);
}
}
}
总结
以上内容详细介绍了 Yii2 在控制器中验证请求参数的优化使用方法,希望能对大家有所帮助。如有任何疑问,欢迎留言交流,小编会及时回复。感谢大家对本站的支持!如果觉得本文对您有帮助,欢迎转载,请注明出处,谢谢!