学习yii2.0框架阅读代码(七)

vendor/yiisoft/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 <[email protected]>
 * @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;
    }

    /**
     * Returns the form name that this model class should use.
     *
     * 返回表单的名称,就是这个 model 的类名
     *
     * The form name is mainly used by [[\yii\widgets\ActiveForm]] to determine how to name
     * the input fields for the attributes in a model. If the form name is "A" and an attribute
     * name is "b", then the corresponding input name would be "A[b]". If the form name is
     * an empty string, then the input name would be "b".
     *
     * By default, this method returns the model class name (without the namespace part)
     * as the form name. You may override it when the model is used in different forms.
     *
     * @return string the form name of this model class.
     */
    public function formName()
    {
        // ReflectionClass 类包含了一个类的有关信息
        $reflector = new ReflectionClass($this);
        // 获取类的短名,就是不含命名空间(namespace)的那一部分
        return $reflector->getShortName();
    }

    /**
     * Returns the list of attribute names.
     * 返回属性名的列表,注意:只会返回 public 且不是 static 的属性
     * By default, this method returns all public non-static properties of the class.
     * You may override this method to change the default behavior.
     * @return array list of attribute names.
     */
    public function attributes()
    {
        $class = new ReflectionClass($this);
        $names = [];
        // ReflectionClass::getProperties — 获取一组属性
        // ReflectionProperty::IS_STATIC 指示了 static 的属性。
        // ReflectionProperty::IS_PUBLIC 指示了 public 的属性。
        // ReflectionProperty::IS_PROTECTED 指示了 protected 的属性。
        // ReflectionProperty::IS_PRIVATE 指示了 private 的属性。
        foreach ($class->getProperties(\ReflectionProperty::IS_PUBLIC) as $property) {
            // 如果是public的属性,并且不是static的,就认为是它的attribute
            if (!$property->isStatic()) {
                // 获取该属性的名称
                $names[] = $property->getName();
            }
        }

        return $names;
    }
时间: 2024-10-22 10:16:21

学习yii2.0框架阅读代码(七)的相关文章

学习yii2.0框架阅读代码(四)

阅读 BaseYii Yii的辅助类核心框架 别名相关(续) //用一个真实的路径注册一个别名 public static function setAlias($alias, $path) { if (strncmp($alias, '@', 1)) { // 如果不是以 @ 开头,就将 @ 拼到开头 $alias = '@' . $alias; } // 获取 / 在 $alias 中首次出现的位置 $pos = strpos($alias, '/'); // 如果 / 不存在,$root 就

学习yii2.0框架阅读代码(十七)

vendor/yiisoft/yii2/base/Module. 模块类 每个模块都有一个继承yii\base\Module的模块类,该类文件直接放在模块的yii\base\Module::basePath目录下, 并且能被自动加载.当一个模块被访问,和应用主题实例类似会创建该模块类唯一实例,模块实例用来帮模块内代码共享数据和组件 class Module extends ServiceLocator { /** * @event 在执行ActionEvent方法时触发事件 * 你可以设置[[A

学习yii2.0框架阅读代码(三)

阅读 BaseYii Yii的辅助类核心框架 别名相关 <?php namespace yii; //定义命名空间,昨天修改了一天.. use yii\base\InvalidConfigException; use yii\base\InvalidParamException; use yii\base\UnknownClassException; use yii\log\Logger; use yii\di\Container; //获取应用程序开始时间 defined('YII_BEGIN

学习yii2.0框架阅读代码(十一)

vendor/yiisoft/yii2/base/Module. php(续) /** * 该方法解析指定的路线和创建相应的子模块(s),控制器和行动 * This method parses the specified route and creates the corresponding child module(s), controller and action * instances. It then calls [[Controller::runAction()]] to run th

学习yii2.0框架阅读代码(十五)

行为是 yii\base\Behavior 或其子类的实例.行为,也称为mixins,可以无须改变类继承关系即可增强一个已有的 yii\base\Component 类功能.当行为附加到组件后,它将“注入”它的方法和属性到组件,然后可以像访问组件内定义的方法和属性一样访问它们.此外,行为通过组件能响应被触发的事件,从而自定义或调整组件正常执行的代码. <?php namespace yii\base; /** * 行为是所有行为类的基类. * * 一个行为可以用来增强现有的功能组件,无需修改其代

学习yii2.0框架阅读代码(六)

vendor/yiisoft/yii2/base/ArrayableTrait. <?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 yii\helpers\ArrayHelper; use

学习yii2.0框架阅读代码(二十)

vendor/yiisoft/yii2/base/Module. php(续) /** * 新建一个控制器实例基于给定的路线. * * 路线应该是相对于这个模块.该方法实现了以下算法 * to resolve the given route: * * 1. If the route is empty, use [[defaultRoute]]; * 2. If the first segment of the route is a valid module ID as declared in [

学习yii2.0框架阅读代码(二十一)

vendor/yiisoft/yii2/base/Module.php(完) /** * 创建一个控制器基于给定控制器ID. * * The controller ID is relative to this module. The controller class * should be namespaced under [[controllerNamespace]]. * * Note that this method does not check [[modules]] or [[cont

学习yii2.0框架阅读代码(十九)

vendor/yiisoft/yii2/base/Module. php(续) /** * 检索指定的子模块ID. * 这种方法支持检索两个子模块和子模块. * @param string $id module ID (case-sensitive). To retrieve grand child modules, * use ID path relative to this module (e.g. `admin/content`). * @param boolean $load wheth