国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 語言 > PHP > 正文

yii2 在控制器中驗證請求參數的使用方法

2024-05-05 00:09:44
字體:
來源:轉載
供稿:網友

寫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() 方法,主要功能:

  • 驗證規則可從對象外部進行設置。
  • 從驗證規則中獲取可賦值的屬性。
<?phpnamespace 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;  }}

定義參數驗證服務類

定義參數驗證服務類,主要功能有:

  • 設置參數列表和參數規則列表。
  • 使用 參數驗證模型 進行驗證和存儲驗證錯誤消息。
  • 使用魔術方法獲取 參數驗證模型 中的驗證錯誤消息。
<?phpnamespace 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 在控制器中驗證請求參數的使用方法,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對VeVb武林網網站的支持!
如果你覺得本文對你有幫助,歡迎轉載,煩請注明出處,謝謝!


注:相關教程知識閱讀請移步到PHP教程頻道。
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表

圖片精選

主站蜘蛛池模板: 宿州市| 凌源市| 姚安县| 延安市| 建水县| 垦利县| 溆浦县| 华宁县| 东至县| 香格里拉县| 班戈县| 江津市| 宁阳县| 岳西县| 梁平县| 长泰县| 台东县| 南充市| 连南| 宁明县| 德化县| 申扎县| 盖州市| 武穴市| 临潭县| 阿拉善右旗| 汉阴县| 恭城| 小金县| 余江县| 永泰县| 泗阳县| 东辽县| 南皮县| 琼结县| 晋城| 黑河市| 商水县| 定西市| 兴海县| 哈巴河县|