Behvaior类,Behavior类是所有事件类的基类:

目录yii2\base\Behavior.php

 <?php
/**
* @link http://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC
* @license http://www.yiiframework.com/license/
*/ namespace yii\base; /**
* Behavior is the base class for all behavior classes.
* 所有行为的基类
* A behavior can be used to enhance the functionality of an existing component without modifying its code.
* In particular, it can "inject" its own methods and properties into the component
* and make them directly accessible via the component. It can also respond to the events triggered in the component
* and thus intercept the normal code execution.
* 用来增强现有组件的功能而不修改它的代码。它可以添加自己的方法和属性组件
* 使他们可以直接通过组件访问。还可以响应组件触发的事件,拦截正常的代码执行。
* @author Qiang Xue <qiang.xue@gmail.com>
* @since 2.0
* 继承父类Object
*/
class Behavior extends Object
{
/**
* @var Component the owner of this behavior 要附加行为对象的组件。
*/
public $owner; /**
* Declares event handlers for the [[owner]]'s events.
* 声明[[owner]]的事件处理程序
* Child classes may override this method to declare what PHP callbacks should
* be attached to the events of the [[owner]] component.
* 子类可以重写此方法 php回调应连接 [[owner]]组件。
* The callbacks will be attached to the [[owner]]'s events when the behavior is
* attached to the owner; and they will be detached from the events when
* the behavior is detached from the component.
* 当行为被连接到owner时回调将附在[[owner]]的事件中,当行为从组件中分离时,它们将被分离
* The callbacks can be any of the followings:
*
* - method in this behavior: `'handleClick'`, equivalent to `[$this, 'handleClick']`
* - object method: `[$object, 'handleClick']`
* - static method: `['Page', 'handleClick']`
* - anonymous function: `function ($event) { ... }`
*
* The following is an example:
*
* ~~~
* [
* Model::EVENT_BEFORE_VALIDATE => 'myBeforeValidate',
* Model::EVENT_AFTER_VALIDATE => 'myAfterValidate',
* ]
* ~~~
*
* @return array events (array keys) and the corresponding event handler methods (array values).
* 事件和相应的事件处理方法
*/
public function events()
{
return [];
} /**
* Attaches the behavior object to the component.绑定行为到组件
* The default implementation will set the [[owner]] property
* and attach event handlers as declared in [[events]].
* 默认设置[[owner]]属性并将事件处理程序绑定到组件
* Make sure you call the parent implementation if you override this method. 如果重写方法,确保调用父类去实现
* @param Component $owner the component that this behavior is to be attached to. 行为绑定到$owner组件
*/
public function attach($owner)
{
$this->owner = $owner;//设置 $owner ,使得所依附的对象可以访问、操作
foreach ($this->events() as $event => $handler) {
//将准备响应的事件,通过所依附类的 on()方法 绑定到类上
$owner->on($event, is_string($handler) ? [$this, $handler] : $handler);
}
} /**
* Detaches the behavior object from the component. 解除绑定的行为
* The default implementation will unset the [[owner]] property 默认取消 owner的属性
* and detach event handlers declared in [[events]]. 将events中的事件程序解除绑定
* Make sure you call the parent implementation if you override this method.如果重写方法,确保调用父类去实现
*/
public function detach()
{
if ($this->owner) {
foreach ($this->events() as $event => $handler) {//遍历行为中 events() 返回的数组
//通过Component的 off() 将绑定到类上的事件解除
$this->owner->off($event, is_string($handler) ? [$this, $handler] : $handler);
}
$this->owner = null;//将 $owner 设置为 null ,表示这个解除绑定
}
}
}

接下来看一下model类,它是所有模型的基类

目录yii2\base\Model.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;
use ArrayAccess;
use ArrayObject;
use ArrayIterator;
use ReflectionClass;
use IteratorAggregate;
use yii\helpers\Inflector;
use yii\validators\RequiredValidator;
use yii\validators\Validator; /**
* Model is the base class for data models.
*
* IteratorAggregate(聚合式迭代器)接口 — 创建外部迭代器的接口, 需实现 getIterator 方法。
* IteratorAggregate::getIterator — 获取一个外部迭代器, foreach 会调用该方法。
*
* ArrayAccess(数组式访问)接口 — 提供像访问数组一样访问对象的能力的接口, 需实现如下方法:
* ArrayAccess::offsetExists — 检查一个偏移位置是否存在
* ArrayAccess::offsetGet — 获取一个偏移位置的值
* ArrayAccess::offsetSet — 设置一个偏移位置的值
* ArrayAccess::offsetUnset — 复位一个偏移位置的值
* 在 Model 中用于实现将 $model[$field] 替换为 $model->$field
*
* Model implements the following commonly used features:
*
* - attribute declaration: by default, every public class member is considered as
* a model attribute
* - attribute labels: each attribute may be associated with a label for display purpose
* - massive attribute assignment
* - scenario-based validation
*
* Model also raises the following events when performing data validation:
*
* - [[EVENT_BEFORE_VALIDATE]]: an event raised at the beginning of [[validate()]]
* - [[EVENT_AFTER_VALIDATE]]: an event raised at the end of [[validate()]]
*
* You may directly use Model to store model data, or extend it with customization.
*
* @property \yii\validators\Validator[] $activeValidators The validators applicable to the current
* [[scenario]]. This property is read-only.
* @property array $attributes Attribute values (name => value).
* @property array $errors An array of errors for all attributes. Empty array is returned if no error. The
* result is a two-dimensional array. See [[getErrors()]] for detailed description. This property is read-only.
* @property array $firstErrors The first errors. The array keys are the attribute names, and the array values
* are the corresponding error messages. An empty array will be returned if there is no error. This property is
* read-only.
* @property ArrayIterator $iterator An iterator for traversing the items in the list. This property is
* read-only.
* @property string $scenario The scenario that this model is in. Defaults to [[SCENARIO_DEFAULT]].
* @property ArrayObject|\yii\validators\Validator[] $validators All the validators declared in the model.
* This property is read-only.
*
* @author Qiang Xue <qiang.xue@gmail.com>
* @since 2.0
*/
class Model extends Component implements IteratorAggregate, ArrayAccess, Arrayable
{
use ArrayableTrait; /**
* The name of the default scenario.
* 默认场景的名称
*/
const SCENARIO_DEFAULT = 'default';
/**
* @event ModelEvent an event raised at the beginning of [[validate()]]. You may set
* [[ModelEvent::isValid]] to be false to stop the validation.
*/
const EVENT_BEFORE_VALIDATE = 'beforeValidate';
/**
* @event Event an event raised at the end of [[validate()]]
*/
const EVENT_AFTER_VALIDATE = 'afterValidate'; /**
* @var array validation errors (attribute name => array of errors)
* 验证的错误信息
*/
private $_errors;
/**
* @var ArrayObject list of validators
*/
private $_validators;
/**
* @var string current scenario
* 当前的场景,默认是default
*/
private $_scenario = self::SCENARIO_DEFAULT; /**
* Returns the validation rules for attributes.
*
* 返回属性的验证规则
*
* Validation rules are used by [[validate()]] to check if attribute values are valid.
* Child classes may override this method to declare different validation rules.
*
* Each rule is an array with the following structure:
*
* ~~~
* [
* ['attribute1', 'attribute2'],
* 'validator type',
* 'on' => ['scenario1', 'scenario2'],
* ...other parameters...
* ]
* ~~~
*
* where
*
* - attribute list: required, specifies the attributes array to be validated, for single attribute you can pass string;
* - validator type: required, specifies the validator to be used. It can be a built-in validator name,
* a method name of the model class, an anonymous function, or a validator class name.
* - on: optional, specifies the [[scenario|scenarios]] array when the validation
* rule can be applied. If this option is not set, the rule will apply to all scenarios.
* - additional name-value pairs can be specified to initialize the corresponding validator properties.
* Please refer to individual validator class API for possible properties.
*
* A validator can be either an object of a class extending [[Validator]], or a model class method
* (called *inline validator*) that has the following signature:
*
* ~~~
* // $params refers to validation parameters given in the rule
* function validatorName($attribute, $params)
* ~~~
*
* In the above `$attribute` refers to currently validated attribute name while `$params` contains an array of
* validator configuration options such as `max` in case of `string` validator. Currently validate attribute value
* can be accessed as `$this->[$attribute]`.
*
* Yii also provides a set of [[Validator::builtInValidators|built-in validators]].
* They each has an alias name which can be used when specifying a validation rule.
*
* Below are some examples:
*
* ~~~
* [
* // built-in "required" validator
* [['username', 'password'], 'required'],
* // built-in "string" validator customized with "min" and "max" properties
* ['username', 'string', 'min' => 3, 'max' => 12],
* // built-in "compare" validator that is used in "register" scenario only
* ['password', 'compare', 'compareAttribute' => 'password2', 'on' => 'register'],
* // an inline validator defined via the "authenticate()" method in the model class
* ['password', 'authenticate', 'on' => 'login'],
* // a validator of class "DateRangeValidator"
* ['dateRange', 'DateRangeValidator'],
* ];
* ~~~
*
* Note, in order to inherit rules defined in the parent class, a child class needs to
* merge the parent rules with child rules using functions such as `array_merge()`.
*
* @return array validation rules
* @see scenarios()
*/
public function rules()
{
return [];
} /**
* Returns a list of scenarios and the corresponding active attributes.
* An active attribute is one that is subject to validation in the current scenario.
* 返回场景及与之对应的 active 属性的列表
* The returned array should be in the following format:
*
* ~~~
* [
* 'scenario1' => ['attribute11', 'attribute12', ...],
* 'scenario2' => ['attribute21', 'attribute22', ...],
* ...
* ]
* ~~~
*
* By default, an active attribute is considered safe and can be massively assigned.
* If an attribute should NOT be massively assigned (thus considered unsafe),
* please prefix the attribute with an exclamation character (e.g. '!rank').
*
* The default implementation of this method will return all scenarios found in the [[rules()]]
* declaration. A special scenario named [[SCENARIO_DEFAULT]] will contain all attributes
* found in the [[rules()]]. Each scenario will be associated with the attributes that
* are being validated by the validation rules that apply to the scenario.
*
* @return array a list of scenarios and the corresponding active attributes.
*/
public function scenarios()
{
// 默认有 default 的场景
$scenarios = [self::SCENARIO_DEFAULT => []];
foreach ($this->getValidators() as $validator) {
// 循环 validator,取出所有提到的场景,包括 on 和 except
foreach ($validator->on as $scenario) {
$scenarios[$scenario] = [];
}
foreach ($validator->except as $scenario) {
$scenarios[$scenario] = [];
}
}
// 取出所有场景的名称
$names = array_keys($scenarios); foreach ($this->getValidators() as $validator) {
if (empty($validator->on) && empty($validator->except)) {
// 如果 validator 即没有定义 on,也没有定义 except,就放到所有的场景中
foreach ($names as $name) {
// 循环 $validator 的所有属性
foreach ($validator->attributes as $attribute) {
$scenarios[$name][$attribute] = true;
}
}
} elseif (empty($validator->on)) {
// 如果没有定义 on
foreach ($names as $name) {
if (!in_array($name, $validator->except, true)) {
// 而且场景不在 except 中, 就将这个属性加入到相应的场景中
foreach ($validator->attributes as $attribute) {
$scenarios[$name][$attribute] = true;
}
}
}
} else {
// 如果定义了 on
foreach ($validator->on as $name) {
// 就将这个属性加入到 on 定义的场景中
foreach ($validator->attributes as $attribute) {
$scenarios[$name][$attribute] = true;
}
}
}
} /**
* 将 $scenarios 从
*
* ~~~
* [
* 'default' => [],
* 'scenario1' => ['attribute11' => true, 'attribute12' => true, ...],
* 'scenario2' => ['attribute21' => true, 'attribute22' => true, ...],
* 'scenario3' => [],
* ...
* ]
* ~~~
* 转化为
* ~~~
* [
* 'default' => [],
* 'scenario1' => ['attribute11', 'attribute12', ...],
* 'scenario2' => ['attribute21', 'attribute22', ...],
* ...
* ]
* ~~~
*/
foreach ($scenarios as $scenario => $attributes) {
// 去除掉没有属性值的场景
if (empty($attributes) && $scenario !== self::SCENARIO_DEFAULT) {
unset($scenarios[$scenario]);
} else {
// 取出场景中的属性名称
$scenarios[$scenario] = array_keys($attributes);
}
} return $scenarios;
}

未完待续

yii2源码学习笔记(六)的更多相关文章

  1. yii2源码学习笔记(九)

    Application是所有应用程序类的基类,接下来了解一下它的源码.yii2\base\Application.php. <?php /** * @link http://www.yiifra ...

  2. yii2源码学习笔记(八)

    Action是所有控制器的基类,接下来了解一下它的源码.yii2\base\Action.php <?php /** * @link http://www.yiiframework.com/ * ...

  3. 老刘 Yii2 源码学习笔记之 Action 类

    Action 的概述 InlineAction 就是内联动作,所谓的内联动作就是放到controller 里面的 actionXXX 这种 Action.customAction 就是独立动作,就是直 ...

  4. yii2源码学习笔记(十六)

    Module类的最后代码 /** * Registers sub-modules in the current module. * 注册子模块到当前模块 * Each sub-module shoul ...

  5. yii2源码学习笔记(二十)

    Widget类是所有部件的基类.yii2\base\Widget.php <?php /** * @link http://www.yiiframework.com/ * @copyright ...

  6. yii2源码学习笔记(十八)

    View继承了component,用于渲染视图文件:yii2\base\View.php <?php /** * @link http://www.yiiframework.com/ * @co ...

  7. yii2源码学习笔记(十七)

    Theme 类,应用的主题,通过替换路径实现主题的应用,方法为获取根路径和根链接:yii2\base\Theme.php <?php /** * @link http://www.yiifram ...

  8. yii2源码学习笔记(十四)

    Module类是模块和应用类的基类. yiisoft\yii2\base\Module.php <?php /** * @link http://www.yiiframework.com/ * ...

  9. yii2源码学习笔记(十三)

    模型类DynamicModel主要用于实现模型内的数据验证yii2\base\DynamicModel.php <?php /** * @link http://www.yiiframework ...

随机推荐

  1. qut训练题解-2016-9-4个人赛

    题目链接:http://acm.hust.edu.cn/vjudge/contest/131124#overview 贴了链接这里就不上原题的描述了. A: B: 分析:这里用到简单的拓扑排序的算法. ...

  2. 南京Uber优步司机奖励政策(1月18日~1月24日)

    滴快车单单2.5倍,注册地址:http://www.udache.com/ 如何注册Uber司机(全国版最新最详细注册流程)/月入2万/不用抢单:http://www.cnblogs.com/mfry ...

  3. Relocation - POJ 2923(状态压缩+01背包)

    题目大意:有个人需要搬家,有N件物品,给个物品的重量是 w[i] 然后又两个车,每个车的载重量分别是C1和C2,求最少需要运输多少次才能把这些物品全部运输完毕. 分析:刚开始就发现物品数不多,想着直接 ...

  4. nyoj 329 循环小数【KMP】【求最小循环节长度+循环次数+循环体】

    循环小数 时间限制:3000 ms  |  内存限制:65535 KB 难度:1   描述 我们可爱的 c小加 近段儿正在潜心研究数学,当他学习到循环小数这一部分时不是太明白循环体是什么意思(比如说3 ...

  5. 关于assert的学习

    编写代码时,总会做出一些假设,断言就是用于在代码中捕捉这些假设, 可以将断言看成是异常处理的一种高级形式. c语言assert宏的定义, #include <assert.h> void ...

  6. 基于XMPP实现的Openfire的配置安装+Android客户端的实现[转]

    最近在整理一些这方面的资料,闲话少说,咱还是直奔主题吧 :) http://blog.csdn.net/sk719887916/article/details/40541163 https://git ...

  7. MySQL 5.6初始配置调整

    原文链接: What to tune in MySQL 5.6 after installation原文日期: 2013年09月17日翻译日期: 2014年06月01日翻译人员: 铁锚 随着 大量默认 ...

  8. winserve2008下不能运行winXP下开发的应用程序→更改“兼容性”

    winserve2008下不能运行winXP下开发的应用程序 对策:更该“兼容性”

  9. Objective-C中的@Property详解

    Objective-C中的@Property详解 @Property (属性) class vairs 这个属性有nonatomic, strong, weak, retain, copy等等 我把它 ...

  10. Python中sys.argv[]的用法

    类似bash中的$0, $1, $2... sys.argv[0]:文件名 sys.argv[1]:第一个参数 sys.argv[2]:第二个参数 import sys print "The ...