热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

yii2源码学习笔记(十三)

yii2源码学习笔记(十三)
模型类DynamicModel主要用于实现模型内的数据验证yii2\base\DynamicModel.php

  1 php
  2 /**
  3  * @link http://www.yiiframework.com/
  4  * @copyright Copyright (c) 2008 Yii Software LLC
  5  * @license http://www.yiiframework.com/license/
  6  */
  7 namespace yii\base;
  8 
  9 use yii\validators\Validator;
 10 
 11 /**
 12  * DynamicModel is a model class primarily used to support ad hoc data validation.
 13  * DynamicModel是一种主要用于支持ad hoc数据验证模型类
 14  * The typical usage of DynamicModel is as follows,
 15  *
 16  * "php
 17  * public function actionSearch($name, $email)
 18  * {
 19  *     $model = DynamicModel::validateData(compact('name', 'email'), [
 20  *         [['name', 'email'], 'string', 'max' => 128],
 21  *         ['email', 'email'],
 22  *     ]);
 23  *     if ($model->hasErrors()) {
 24  *         // validation fails
 25  *     } else {
 26  *         // validation succeeds
 27  *     }
 28  * }
 29  * "
 30  *
 31  * The above example shows how to validate `$name` and `$email` with the help of DynamicModel.
 32  * 上面的例子演示了如何用DynamicModel验证用户名`$name`和邮箱`$email`
 33  * The [[validateData()]] method creates an instance of DynamicModel, defines the attributes
 34  * using the given data (`name` and `email` in this example), and then calls [[Model::validate()]].
 35  * validateData() 方法会创建一个 DynamicModel 的实例对象。通过给定数据定义模型特性,之后调用Model::validate() 方法。
 36  * You can check the validation result by [[hasErrors()]], like you do with a normal model.
 37  * You may also access the dynamic attributes defined through the model instance, e.g.,
 38  * 可以通过[[hasErrors()]]方法获取验证结果
 39  * `$model->name` and `$model->email`.
 40  *
 41  * Alternatively, you may use the following more "classic" syntax to perform ad-hoc data validation:
 42  *  除此之外,你也可以用如下的更加“classic(传统)”的语法来执行临时数据验
 43  * "php
 44  * $model = new DynamicModel(compact('name', 'email'));
 45  * $model->addRule(['name', 'email'], 'string', ['max' => 128])
 46  *     ->addRule('email', 'email')
 47  *     ->validate();
 48  * "
 49  *
 50  * DynamicModel implements the above ad-hoc data validation feature by supporting the so-called
 51  * "dynamic attributes". It basically allows an attribute to be defined dynamically through its constructor
 52  * or [[defineAttribute()]].
 53  * 实现了上述特殊数据模型验证功能支持的“动态属性”。允许通过它的构造函数或 [[defineAttribute()]]来定义一个属性
 54  * @author Qiang Xue 
 55  * @since 2.0
 56  */
 57 class DynamicModel extends Model
 58 {
 59     private $_attributes = [];//动态模型内动态属性
 60 
 61 
 62     /**
 63      * Constructors.构造函数,用于将传入的属性赋值给_attributes,便于使用
 64      * @param array $attributes the dynamic attributes (name-value pairs, or names) being defined被定义的动态属性
 65      * @param array $config the configuration array to be applied to this object.用于该对象的配置数组。
 66      */
 67     public function __construct(array $attributes = [], $cOnfig= [])
 68     {
 69         foreach ($attributes as $name => $value) {//遍历传入的属性
 70             if (is_integer($name)) {//如果是整型,说明只传入了属性名,将属性名写入_attributes
 71                 $this->_attributes[$value] = null;
 72             } else {
 73                 $this->_attributes[$name] = $value;//按键值对的形式写入
 74             }
 75         }
 76         parent::__construct($config);//调用父类的配置
 77     }
 78 
 79     /**
 80      * @inheritdoc 重写__get方法,从_attributes中取值
 81      */
 82     public function __get($name)
 83     {
 84         if (array_key_exists($name, $this->_attributes)) {
 85             //如果传入的$name在数组_attributes中存在,则从_attributes中取值
 86             return $this->_attributes[$name];
 87         } else {//否则调用父类的__get方法取属性值
 88             return parent::__get($name);
 89         }
 90     }
 91 
 92     /**
 93      * @inheritdoc 重写__set方法,给_attributes设置值
 94      */
 95     public function __set($name, $value)
 96     {
 97         if (array_key_exists($name, $this->_attributes)) {
 98             //如果传入的$name在数组_attributes中存在,则将动态属性$name的值设置为$value
 99             $this->_attributes[$name] = $value;
100         } else {
101             parent::__set($name, $value);//调用父类的__set方法设置属性值
102         }
103     }
104 
105     /**
106      * @inheritdoc 同上 重写__isset方法,判断_attributes中是否设置$name值
107      */
108     public function __isset($name)
109     {
110         if (array_key_exists($name, $this->_attributes)) {
111             return isset($this->_attributes[$name]);
112         } else {
113             return parent::__isset($name);
114         }
115     }
116 
117     /**
118      * @inheritdoc 同上,重写__unset方法,删除_attributes中的$name属性值
119      */
120     public function __unset($name)
121     {
122         if (array_key_exists($name, $this->_attributes)) {
123             unset($this->_attributes[$name]);
124         } else {
125             parent::__unset($name);
126         }
127     }
128 
129     /**
130      * Defines an attribute. 定义动态属性的方法
131      * @param string $name the attribute name   属性名
132      * @param mixed $value the attribute value  属性值
133      */
134     public function defineAttribute($name, $value = null)
135     {
136         $this->_attributes[$name] = $value;
137     }
138 
139     /**
140      * Undefines an attribute. 用于删除动态属性的方法
141      * @param string $name the attribute name 属性名
142      */
143     public function undefineAttribute($name)
144     {
145         unset($this->_attributes[$name]);
146     }
147 
148     /**
149      * Adds a validation rule to this model.    添加验证规则
150      * You can also directly manipulate [[validators]] to add or remove validation rules.
151      * This method provides a shortcut.
152      * 可以直接调用[[validators]]来添加或者删除验证规则,本方法提供了一个短方法
153      * @param string|array $attributes the attribute(s) to be validated by the rule 进行验证的属性
154      * @param mixed $validator the validator for the rule.This can be a built-in validator name,
155      * a method name of the model class, an anonymous function, or a validator class name.
156      * 规则的验证。这是一个内置验证器的名字, 一个模型类的方法名,一个匿名函数或一个验证器类的名称。
157      * @param array $options the options (name-value pairs) to be applied to the validator
158      *  (name-value)被应用到验证器
159      * @return static the model itself  模型本身
160      */
161     public function addRule($attributes, $validator, $optiOns= [])
162     {
163         $validators = $this->getValidators();//所有的验证规则对象
164         //生成Validator对象,并且插入 $validators中
165         $validators->append(Validator::createValidator($validator, $this, (array) $attributes, $options));
166 
167         return $this;
168     }
169 
170     /**
171      * Validates the given data with the specified validation rules.通过指定的规则验证给定的数据
172      * This method will create a DynamicModel instance, populate it with the data to be validated,
173      * create the specified validation rules, and then validate the data using these rules.
174      * @param array $data the data (name-value pairs) to be validated
175      * @param array $rules the validation rules. Please refer to [[Model::rules()]] on the format of this parameter.
176      * @return static the model instance that contains the data being validated
177      * @throws InvalidConfigException if a validation rule is not specified correctly.
178      */
179     public static function validateData(array $data, $rules = [])
180     {
181         /* @var $model DynamicModel */
182         $model = new static($data);//实例化调用类,将$data赋值给_attributes
183         if (!empty($rules)) {
184             $validators = $model->getValidators();//获取所有定义的验证规则
185             foreach ($rules as $rule) {
186                 if ($rule instanceof Validator) {
187                     $validators->append($rule);//如果$rule是Validator的实例,则添加到$validators中
188                 } elseif (is_array($rule) && isset($rule[0], $rule[1])) { // attributes, validator type
189                      //如果$rule是数组,则判断动态属性和验证类型是否存在,创建Validator对象,添加到$validators中
190                     $validator = Validator::createValidator($rule[1], $model, (array) $rule[0], array_slice($rule, 2));
191                     $validators->append($validator);
192                 } else {//抛出异常
193                     throw new InvalidConfigException('Invalid validation rule: a rule must specify both attribute names and validator type.');
194                 }
195             }
196         }
197 
198         $model->validate();//执行验证
199 
200         return $model;
201     }
202 
203     /**
204      * @inheritdoc  返回所有的动态属性
205      */
206     public function attributes()
207     {
208         return array_keys($this->_attributes);
209     }
210 }


推荐阅读
  • 2018年人工智能大数据的爆发,学Java还是Python?
    本文介绍了2018年人工智能大数据的爆发以及学习Java和Python的相关知识。在人工智能和大数据时代,Java和Python这两门编程语言都很优秀且火爆。选择学习哪门语言要根据个人兴趣爱好来决定。Python是一门拥有简洁语法的高级编程语言,容易上手。其特色之一是强制使用空白符作为语句缩进,使得新手可以快速上手。目前,Python在人工智能领域有着广泛的应用。如果对Java、Python或大数据感兴趣,欢迎加入qq群458345782。 ... [详细]
  • 如何实现织梦DedeCms全站伪静态
    本文介绍了如何通过修改织梦DedeCms源代码来实现全站伪静态,以提高管理和SEO效果。全站伪静态可以避免重复URL的问题,同时通过使用mod_rewrite伪静态模块和.htaccess正则表达式,可以更好地适应搜索引擎的需求。文章还提到了一些相关的技术和工具,如Ubuntu、qt编程、tomcat端口、爬虫、php request根目录等。 ... [详细]
  • 本文介绍了在Python3中如何使用选择文件对话框的格式打开和保存图片的方法。通过使用tkinter库中的filedialog模块的asksaveasfilename和askopenfilename函数,可以方便地选择要打开或保存的图片文件,并进行相关操作。具体的代码示例和操作步骤也被提供。 ... [详细]
  • 本文描述了作者第一次参加比赛的经历和感受。作者是小学六年级时参加比赛的唯一选手,感到有些紧张。在比赛期间,作者与学长学姐一起用餐,在比赛题目中遇到了一些困难,但最终成功解决。作者还尝试了一款游戏,在回程的路上感到晕车。最终,作者以110分的成绩取得了省一会的资格,并坚定了继续学习的决心。 ... [详细]
  • 本文介绍了在开发Android新闻App时,搭建本地服务器的步骤。通过使用XAMPP软件,可以一键式搭建起开发环境,包括Apache、MySQL、PHP、PERL。在本地服务器上新建数据库和表,并设置相应的属性。最后,给出了创建new表的SQL语句。这个教程适合初学者参考。 ... [详细]
  • 基于layUI的图片上传前预览功能的2种实现方式
    本文介绍了基于layUI的图片上传前预览功能的两种实现方式:一种是使用blob+FileReader,另一种是使用layUI自带的参数。通过选择文件后点击文件名,在页面中间弹窗内预览图片。其中,layUI自带的参数实现了图片预览功能。该功能依赖于layUI的上传模块,并使用了blob和FileReader来读取本地文件并获取图像的base64编码。点击文件名时会执行See()函数。摘要长度为169字。 ... [详细]
  • 搭建Windows Server 2012 R2 IIS8.5+PHP(FastCGI)+MySQL环境的详细步骤
    本文详细介绍了搭建Windows Server 2012 R2 IIS8.5+PHP(FastCGI)+MySQL环境的步骤,包括环境说明、相关软件下载的地址以及所需的插件下载地址。 ... [详细]
  • PHP图片截取方法及应用实例
    本文介绍了使用PHP动态切割JPEG图片的方法,并提供了应用实例,包括截取视频图、提取文章内容中的图片地址、裁切图片等问题。详细介绍了相关的PHP函数和参数的使用,以及图片切割的具体步骤。同时,还提供了一些注意事项和优化建议。通过本文的学习,读者可以掌握PHP图片截取的技巧,实现自己的需求。 ... [详细]
  • 关羽败走麦城时路过马超封地 马超为何没有出手救人
    对当年关羽败走麦城,恰好路过马超的封地,为啥马超不救他?很感兴趣的小伙伴们,趣历史小编带来详细的文章供大家参考。说到英雄好汉,便要提到一本名著了,没错,那就是《三国演义》。书中虽 ... [详细]
  • 本文分享了一个关于在C#中使用异步代码的问题,作者在控制台中运行时代码正常工作,但在Windows窗体中却无法正常工作。作者尝试搜索局域网上的主机,但在窗体中计数器没有减少。文章提供了相关的代码和解决思路。 ... [详细]
  • 本文介绍了使用Java实现大数乘法的分治算法,包括输入数据的处理、普通大数乘法的结果和Karatsuba大数乘法的结果。通过改变long类型可以适应不同范围的大数乘法计算。 ... [详细]
  • PHP设置MySQL字符集的方法及使用mysqli_set_charset函数
    本文介绍了PHP设置MySQL字符集的方法,详细介绍了使用mysqli_set_charset函数来规定与数据库服务器进行数据传送时要使用的字符集。通过示例代码演示了如何设置默认客户端字符集。 ... [详细]
  • Java序列化对象传给PHP的方法及原理解析
    本文介绍了Java序列化对象传给PHP的方法及原理,包括Java对象传递的方式、序列化的方式、PHP中的序列化用法介绍、Java是否能反序列化PHP的数据、Java序列化的原理以及解决Java序列化中的问题。同时还解释了序列化的概念和作用,以及代码执行序列化所需要的权限。最后指出,序列化会将对象实例的所有字段都进行序列化,使得数据能够被表示为实例的序列化数据,但只有能够解释该格式的代码才能够确定数据的内容。 ... [详细]
  • 橱窗设计的表现手法及其应用
    本文介绍了橱窗设计的表现手法,包括直接展示、寓意与联想、夸张与幽默等。通过对商品的折、拉、叠、挂、堆等陈列技巧,橱窗设计能够充分展现商品的形态、质地、色彩、样式等特性。同时,寓意与联想可以通过象形形式或抽象几何道具来唤起消费者的联想与共鸣,创造出强烈的时代气息和视觉空间。合理的夸张和贴切的幽默能够明显夸大商品的美的因素,给人以新颖奇特的心理感受,引起人们的笑声和思考。通过这些表现手法,橱窗设计能够有效地传达商品的个性内涵,吸引消费者的注意力。 ... [详细]
  • HDU 2372 El Dorado(DP)的最长上升子序列长度求解方法
    本文介绍了解决HDU 2372 El Dorado问题的一种动态规划方法,通过循环k的方式求解最长上升子序列的长度。具体实现过程包括初始化dp数组、读取数列、计算最长上升子序列长度等步骤。 ... [详细]
author-avatar
笨蛋說愛我8_382
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有