场景
需要做一个手机号充值的功能,页面上有两个输入框,手机号码与充值的金额。
后端在接收前端传递的手机号与充值金额的时候,需要进行一些格式的判断,比如
<?phpif (empty($_POST['mobile'])){throw new Exception('请输入手机号码');}if (手机号是否合法) ...if (金额是否存在) ...if (金额是否合法) ...
很多的if else的判断,看上去很是不优雅,那么如何在yii中是如何使用model进行避免的呢?
与model(ActiveRecord)的区别
ActiveRecord 是属于ORM,其与数据库表相对应。
而此 Model,也可以称之为Form,是一种数据结构化,接收来自前台、接口的一种数据集合体。
使用model
自定义model
<?phpnamespace app\models;use app\base\Model;class RechargeModel extends Model{public $mobile;public $account;public function rules (){$rules = [];$rules[] = [['mobile','account'],'required'];$rules[] = ['mobile','checkMobile'];$rules[] = ['account','integer','min' => 0];return $rules;}public function attributeLabels (){return ['mobile' => '手机号','account' => '充值金额'];}// 自定义校验规则public function checkMobile ($model, $attribute){// 此处写手机号的校验规则,如果校验失败,则addError进行错误提示if(手机号不合法){$this->addError($attribute, '手机号格式不正确');}}}
简单使用
<?php// 模拟$model = new RechargeModel();$model->mobile = 1;$model->account = -1;var_dump($model->validate(), $model->errors);die;// 正常$model = new RechargeModel();// load的第二个参数如果不是 '',那么前端上传的字段需要为 RechargeModel[mobile] 和 RechargeModel[account]if ($model->load(Yii::$app->request->post(), '') && $model->validate()){// 验证成功// do somethingreturn;}// 验证失败var_dump($model->errors);
