写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() 方法,主要功能:
- 验证规则可从对象外部进行设置。
- 从验证规则中获取可赋值的属性。
<"htmlcode"><"color: #ff0000">总结以上所述是小编给大家介绍的yii2 在控制器中验证请求参数的使用方法,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对网站的支持!
如果你觉得本文对你有帮助,欢迎转载,烦请注明出处,谢谢!
免责声明:本站文章均来自网站采集或用户投稿,网站不提供任何软件下载或自行开发的软件!
如有用户或公司发现本站内容信息存在侵权行为,请邮件告知! 858582#qq.com
桃源资源网 Design By www.nqtax.com
暂无“yii2 在控制器中验证请求参数的使用方法”评论...