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. 折腾iPhone的生活——设置“查找我的iPhone”,让iPhone更防盗

    对于iPhone,防盗一直是一个非常那啥的话题,很多买过iPhone的人都被偷过,但疼,然而苹果也看到了这个问题,所以在iOS7,我们终于看到了一个比较靠谱的防盗软件:查找我的iPhone 之前小偷解 ...

  2. [基础] Loss function(一)

    Loss function = Loss term(误差项) + Regularization term(正则项),我们先来研究误差项:首先,所谓误差项,当然是误差的越少越好,由于不存在负误差,所以为 ...

  3. Sysrq 诊断系统故障 与 gdb 调试core dump

    1. 典型应用场景如:    1)系统进入了挂死状态(如调度出现异常.或系统负荷过重),但仍能响应中断,此时可以通过Sysrq魔术键(c)手工触发panic,结合kdump,就能收集到vmcore信息 ...

  4. Spring IOC配置与应用

    1.     FAQ:不给提示: a)     window – preferences – myeclipse – xml – xml catalog b)     User Specified E ...

  5. mysql 统计 每天累计用户数

    需求: 查出 一段时间每天的累计用户, 数据库这么设计的, 只有一张用户表, 每个用户注册的时间, 每一天的数据是之前的天数累计 select count(id) from r_user where ...

  6. 提高你30%的设计效率的PPT快捷键

    在编辑幻灯片的状态下: [Ctrl]+[A]选择全部对象或幻灯片 [Ctrl]+[B]应用(解除)文本加粗 [Ctrl]+[C]复制 [Ctrl]+[D]快速复制对象 [Ctrl]+[E]段落居中对齐 ...

  7. [Firebase + PWA] Keynote: Progressive Web Apps on Firebase

    Link : Video. 1. Firebase Auth: provides simple login with Github, Google, Facebook, Twittr. Link 2. ...

  8. rsyslog官方文档

    http://www.rsyslog.com/doc/v8-stable/configuration/index.html

  9. 源码解析之–网络层YTKNetwork

    首先 关于网络层最先可能想到的是AFNetworking,或者Swift中的Alamofire,直接使用起来也特别的简单,但是稍复杂的项目如果直接使用就显得不够用了,首先第三方耦合不说,就光散落在各处 ...

  10. 聊一聊Android 6.0的运行时权限

    Android 6.0,代号棉花糖,自发布伊始,其主要的特征运行时权限就很受关注.因为这一特征不仅改善了用户对于应用的使用体验,还使得应用开发者在实践开发中需要做出改变. 没有深入了解运行时权限的开发 ...