yii2源码学习笔记(十三)
模型类DynamicModel主要用于实现模型内的数据验证yii2\base\DynamicModel.php
<?php
/**
* @link http://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC
* @license http://www.yiiframework.com/license/
*/
namespace yii\base; use yii\validators\Validator; /**
* DynamicModel is a model class primarily used to support ad hoc data validation.
* DynamicModel是一种主要用于支持ad hoc数据验证模型类
* The typical usage of DynamicModel is as follows,
*
* ```php
* public function actionSearch($name, $email)
* {
* $model = DynamicModel::validateData(compact('name', 'email'), [
* [['name', 'email'], 'string', 'max' => 128],
* ['email', 'email'],
* ]);
* if ($model->hasErrors()) {
* // validation fails
* } else {
* // validation succeeds
* }
* }
* ```
*
* The above example shows how to validate `$name` and `$email` with the help of DynamicModel.
* 上面的例子演示了如何用DynamicModel验证用户名`$name`和邮箱`$email`
* The [[validateData()]] method creates an instance of DynamicModel, defines the attributes
* using the given data (`name` and `email` in this example), and then calls [[Model::validate()]].
* validateData() 方法会创建一个 DynamicModel 的实例对象。通过给定数据定义模型特性,之后调用Model::validate() 方法。
* You can check the validation result by [[hasErrors()]], like you do with a normal model.
* You may also access the dynamic attributes defined through the model instance, e.g.,
* 可以通过[[hasErrors()]]方法获取验证结果
* `$model->name` and `$model->email`.
*
* Alternatively, you may use the following more "classic" syntax to perform ad-hoc data validation:
* 除此之外,你也可以用如下的更加“classic(传统)”的语法来执行临时数据验
* ```php
* $model = new DynamicModel(compact('name', 'email'));
* $model->addRule(['name', 'email'], 'string', ['max' => 128])
* ->addRule('email', 'email')
* ->validate();
* ```
*
* DynamicModel implements the above ad-hoc data validation feature by supporting the so-called
* "dynamic attributes". It basically allows an attribute to be defined dynamically through its constructor
* or [[defineAttribute()]].
* 实现了上述特殊数据模型验证功能支持的“动态属性”。允许通过它的构造函数或 [[defineAttribute()]]来定义一个属性
* @author Qiang Xue <qiang.xue@gmail.com>
* @since 2.0
*/
class DynamicModel extends Model
{
private $_attributes = [];//动态模型内动态属性 /**
* Constructors.构造函数,用于将传入的属性赋值给_attributes,便于使用
* @param array $attributes the dynamic attributes (name-value pairs, or names) being defined被定义的动态属性
* @param array $config the configuration array to be applied to this object.用于该对象的配置数组。
*/
public function __construct(array $attributes = [], $config = [])
{
foreach ($attributes as $name => $value) {//遍历传入的属性
if (is_integer($name)) {//如果是整型,说明只传入了属性名,将属性名写入_attributes
$this->_attributes[$value] = null;
} else {
$this->_attributes[$name] = $value;//按键值对的形式写入
}
}
parent::__construct($config);//调用父类的配置
} /**
* @inheritdoc 重写__get方法,从_attributes中取值
*/
public function __get($name)
{
if (array_key_exists($name, $this->_attributes)) {
//如果传入的$name在数组_attributes中存在,则从_attributes中取值
return $this->_attributes[$name];
} else {//否则调用父类的__get方法取属性值
return parent::__get($name);
}
} /**
* @inheritdoc 重写__set方法,给_attributes设置值
*/
public function __set($name, $value)
{
if (array_key_exists($name, $this->_attributes)) {
//如果传入的$name在数组_attributes中存在,则将动态属性$name的值设置为$value
$this->_attributes[$name] = $value;
} else {
parent::__set($name, $value);//调用父类的__set方法设置属性值
}
} /**
* @inheritdoc 同上 重写__isset方法,判断_attributes中是否设置$name值
*/
public function __isset($name)
{
if (array_key_exists($name, $this->_attributes)) {
return isset($this->_attributes[$name]);
} else {
return parent::__isset($name);
}
} /**
* @inheritdoc 同上,重写__unset方法,删除_attributes中的$name属性值
*/
public function __unset($name)
{
if (array_key_exists($name, $this->_attributes)) {
unset($this->_attributes[$name]);
} else {
parent::__unset($name);
}
} /**
* Defines an attribute. 定义动态属性的方法
* @param string $name the attribute name 属性名
* @param mixed $value the attribute value 属性值
*/
public function defineAttribute($name, $value = null)
{
$this->_attributes[$name] = $value;
} /**
* Undefines an attribute. 用于删除动态属性的方法
* @param string $name the attribute name 属性名
*/
public function undefineAttribute($name)
{
unset($this->_attributes[$name]);
} /**
* Adds a validation rule to this model. 添加验证规则
* You can also directly manipulate [[validators]] to add or remove validation rules.
* This method provides a shortcut.
* 可以直接调用[[validators]]来添加或者删除验证规则,本方法提供了一个短方法
* @param string|array $attributes the attribute(s) to be validated by the rule 进行验证的属性
* @param mixed $validator the validator for the rule.This can be a built-in validator name,
* a method name of the model class, an anonymous function, or a validator class name.
* 规则的验证。这是一个内置验证器的名字, 一个模型类的方法名,一个匿名函数或一个验证器类的名称。
* @param array $options the options (name-value pairs) to be applied to the validator
* (name-value)被应用到验证器
* @return static the model itself 模型本身
*/
public function addRule($attributes, $validator, $options = [])
{
$validators = $this->getValidators();//所有的验证规则对象
//生成Validator对象,并且插入 $validators中
$validators->append(Validator::createValidator($validator, $this, (array) $attributes, $options)); return $this;
} /**
* Validates the given data with the specified validation rules.通过指定的规则验证给定的数据
* This method will create a DynamicModel instance, populate it with the data to be validated,
* create the specified validation rules, and then validate the data using these rules.
* @param array $data the data (name-value pairs) to be validated
* @param array $rules the validation rules. Please refer to [[Model::rules()]] on the format of this parameter.
* @return static the model instance that contains the data being validated
* @throws InvalidConfigException if a validation rule is not specified correctly.
*/
public static function validateData(array $data, $rules = [])
{
/* @var $model DynamicModel */
$model = new static($data);//实例化调用类,将$data赋值给_attributes
if (!empty($rules)) {
$validators = $model->getValidators();//获取所有定义的验证规则
foreach ($rules as $rule) {
if ($rule instanceof Validator) {
$validators->append($rule);//如果$rule是Validator的实例,则添加到$validators中
} elseif (is_array($rule) && isset($rule[], $rule[])) { // attributes, validator type
//如果$rule是数组,则判断动态属性和验证类型是否存在,创建Validator对象,添加到$validators中
$validator = Validator::createValidator($rule[], $model, (array) $rule[], array_slice($rule, ));
$validators->append($validator);
} else {//抛出异常
throw new InvalidConfigException('Invalid validation rule: a rule must specify both attribute names and validator type.');
}
}
} $model->validate();//执行验证 return $model;
} /**
* @inheritdoc 返回所有的动态属性
*/
public function attributes()
{
return array_keys($this->_attributes);
}
}
yii2源码学习笔记(十三)的更多相关文章
- yii2源码学习笔记(九)
Application是所有应用程序类的基类,接下来了解一下它的源码.yii2\base\Application.php. <?php /** * @link http://www.yiifra ...
- yii2源码学习笔记(八)
Action是所有控制器的基类,接下来了解一下它的源码.yii2\base\Action.php <?php /** * @link http://www.yiiframework.com/ * ...
- 老刘 Yii2 源码学习笔记之 Action 类
Action 的概述 InlineAction 就是内联动作,所谓的内联动作就是放到controller 里面的 actionXXX 这种 Action.customAction 就是独立动作,就是直 ...
- yii2源码学习笔记(二十)
Widget类是所有部件的基类.yii2\base\Widget.php <?php /** * @link http://www.yiiframework.com/ * @copyright ...
- yii2源码学习笔记(十八)
View继承了component,用于渲染视图文件:yii2\base\View.php <?php /** * @link http://www.yiiframework.com/ * @co ...
- yii2源码学习笔记(十七)
Theme 类,应用的主题,通过替换路径实现主题的应用,方法为获取根路径和根链接:yii2\base\Theme.php <?php /** * @link http://www.yiifram ...
- yii2源码学习笔记(十四)
Module类是模块和应用类的基类. yiisoft\yii2\base\Module.php <?php /** * @link http://www.yiiframework.com/ * ...
- yii2源码学习笔记(十一)
Controller控制器类,是所有控制器的基类,用于调用模型和布局. <?php /** * @link http://www.yiiframework.com/ * @copyright C ...
- yii2源码学习笔记(六)
Behvaior类,Behavior类是所有事件类的基类: 目录yii2\base\Behavior.php <?php /** * @link http://www.yiiframework. ...
随机推荐
- 第一个java程序
完成自己的第一个java程序 1.新建一个文本文档,在文本文档中编写自己第一个java程序的代码,代码如下; class hello { public static void main(String[ ...
- 使用ajax代替iframe
相信大多数程序员都跟iframe打过交道,iframe简单,好用.在我用的过程中比较苦逼的是关于iframe高度的设置. 由于子页面内容不确定,页面高度也不确定.于是开始网上的各种搜索,一般有两种:一 ...
- 织梦/dedecms 当文章转载时不需要设置图片水印的设置,取消’图片是否加水印‘的复选框,并且修改如下文件即可生效
当想添加水印是选中“图片是否加水印”复选框即可. 找到include/helpers/image.helper.php这个文件,在里面找到中的if( isset($GLOBALS['needwater ...
- 【转】Java中Vector和ArrayList的区别
首先看这两类都实现List接口,而List接口一共有三个实现类,分别是ArrayList.Vector和LinkedList.List用于存放多个元素,能够维护元素的次序,并且允许元素的重复.3个具体 ...
- 正尝试在 OS 载入程序锁内执行托管代码。不要尝试在 DllMain 或映像初始化函数内执行托管代码,这样做会导致应用程序挂起。
出错提示: 正尝试在 OS 载入程序锁内执行托管代码. 不要尝试在 DllMain 或映像初始化函数内执行托管代码,这样做会导致应用程序挂起. 原因分析: .NET2.0中添加了42种非常强大的调试助 ...
- SpannableString使用详解
TextView算是android开发中最最常用的控件了,有的时候,我们要给一个TextView中的显示的文字设置不同的样式或者响应事件,比如同一个TextView中,有的字是红色,有的字是蓝色,有的 ...
- Redis 集群常见问题
Redis集群相关问题 1:远程连接问题 远程连接保护模式下,需要做一些配置.
- C# MD5 16进制MD5对称加密法
/// <summary> /// MD5 16进制算法 /// </summary> /// <param name="str"></p ...
- android.util.AndroidRuntimeException: requestFeature() must be called before adding content解决办法
最近在学习第一行代码这本书,里面的关于activity生命周期有一段例子,但是我自己用mac上装的as运行一直出问题,看log的话就是android.util.AndroidRuntimeExcept ...
- 跳转界面方法 (runtime实用篇一)
在开发项目中,会有这样变态的需求: 推送:根据服务端推送过来的数据规则,跳转到对应的控制器 feeds列表:不同类似的cell,可能跳转不同的控制器(嘘!产品经理是这样要求:我也不确定会跳转哪个界面哦 ...