yii2 在控制器中驗證請求參數(shù)的使用方法
寫api接口時一般會在控制器中簡單驗證參數(shù)的正確性。
使用yii只帶驗證器(因為比較熟悉)實現(xiàn)有兩種方式(效果都不佳)。
針對每個請求單獨寫個 Model , 定義驗證規(guī)則并進行驗證。 缺點:寫好多參數(shù)驗證的 Model 類。
使用 獨立驗證器 中提到的 $validator->validateValue() 方法直接驗證變量值。缺點:寫實例化很多驗證器對象。
有么有“一勞永逸”的做法,像在 Model 中通過 rules 方法定義驗證規(guī)則并實現(xiàn)快速驗證的呢?有!
使用方法(實現(xiàn)效果)
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));
}
//...
}
}
實現(xiàn)方法
定義參數(shù)驗證模型
定義參數(shù)驗證模型 ParamsValidateModel ,繼承 yii\db\ActiveRecord ,重寫 attributes() 方法,主要功能:
- 驗證規(guī)則可從對象外部進行設(shè)置。
- 從驗證規(guī)則中獲取可賦值的屬性。
<?php
namespace common\models\app;
use yii\db\ActiveRecord;
class ParamsValidateModel extends ActiveRecord
{
/**
* @var array 驗證規(guī)則
*/
private $_rules = [];
private $_attributes = [];
// 設(shè)置驗證規(guī)則
public function setRules($rules)
{
$this->_rules = $rules;
foreach ($rules as $item) {
$this->_attributes = array_unique(array_merge($this->_attributes, (array)$item[0]));
}
}
// 重寫獲取驗證規(guī)則
public function rules()
{
return $this->_rules;
}
// 設(shè)置可用屬性列表
public function attributes()
{
return $this->_attributes;
}
}
定義參數(shù)驗證服務(wù)類
定義參數(shù)驗證服務(wù)類,主要功能有:
- 設(shè)置參數(shù)列表和參數(shù)規(guī)則列表。
- 使用 參數(shù)驗證模型 進行驗證和存儲驗證錯誤消息。
- 使用魔術(shù)方法獲取 參數(shù)驗證模型 中的驗證錯誤消息。
<?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 數(shù)據(jù)項
* @param array $rules 驗證規(guī)則
* @return bool
*/
public function validate($data, $rules)
{
// 添加驗證規(guī)則
$this->model->setRules($rules);
// 設(shè)置參數(shù)
$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);
}
}
}
總結(jié)
以上所述是小編給大家介紹的yii2 在控制器中驗證請求參數(shù)的使用方法,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復(fù)大家的。在此也非常感謝大家對腳本之家網(wǎng)站的支持!
如果你覺得本文對你有幫助,歡迎轉(zhuǎn)載,煩請注明出處,謝謝!
- Yii2設(shè)置默認(rèn)控制器的兩種方法
- Yii2創(chuàng)建控制器(createController)方法詳解
- yii2控制器Controller Ajax操作示例
- Yii2使用$this->context獲取當(dāng)前的Module、Controller(控制器)、Action等
- Yii2框架控制器、路由、Url生成操作示例
- Yii控制器中filter過濾器用法分析
- Yii 框架控制器創(chuàng)建使用及控制器響應(yīng)操作示例
- PHP 基于Yii框架中使用smarty模板的方法詳解
- 在Yii框架中使用PHP模板引擎Twig的例子
- yii框架創(chuàng)建與設(shè)置默認(rèn)控制器并載入模板操作示例
相關(guān)文章
PHP實現(xiàn)AJAX動態(tài)網(wǎng)頁及相關(guān)函數(shù)詳解
ajax其實是利用javascript向服務(wù)器請求數(shù)據(jù),然后局部修改頁面,下面這篇文章主要給大家介紹了關(guān)于PHP實現(xiàn)AJAX動態(tài)網(wǎng)頁及相關(guān)函數(shù)的相關(guān)資料,文中通過實例代碼介紹的非常詳細(xì),需要的朋友可以參考下2022-08-08
php實現(xiàn)JWT(json web token)鑒權(quán)實例詳解
這篇文章主要介紹了php實現(xiàn)JWT(json web token)鑒權(quán)實例詳解,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-11-11
PHP設(shè)計模式之適配器模式(Adapter)原理與用法詳解
這篇文章主要介紹了PHP設(shè)計模式之適配器模式(Adapter)原理與用法,結(jié)合實例形式詳細(xì)分析了適配器模式的概念、原理、使用方法及相關(guān)操作注意事項,需要的朋友可以參考下2019-12-12
Yii2基于Ajax自動獲取表單數(shù)據(jù)的方法
這篇文章主要介紹了Yii2基于Ajax自動獲取表單數(shù)據(jù)的方法,涉及Yii結(jié)合ajax調(diào)用鼠標(biāo)事件動態(tài)查詢表單的相關(guān)技巧,需要的朋友可以參考下2016-08-08
php實現(xiàn)爬取和分析知乎用戶數(shù)據(jù)
本文給大家介紹的是利用php的curl編寫的爬取知乎用戶數(shù)據(jù)的爬蟲,并分析用戶的各種屬性,有需要的小伙伴可以參考下2016-01-01

