Model类,集中整个应用的数据和业务逻辑——

 /**
     * Generates a user friendly attribute label based on the give attribute name.
     * 生成一个对用户友好的属性标签,将属性名中的下划线、破折号、点替换为空格,并且每个单词的首字母大写
     * This is done by replacing underscores, dashes and dots with blanks and
     * changing the first letter of each word to upper case.
     * For example, 'department_name' or 'DepartmentName' will generate 'Department Name'.
     * @param string $name the column name
     * @return string the attribute label
     */
    public function generateAttributeLabel($name)
    {
        //调用Inflector::camel2words()方法生成用户友好的属性标签,属于辅助方法
        return Inflector::camel2words($name, true);
    }

    /**
     * Returns attribute values.
     * 返回属性值,如不指定属性名,则返回所有[[attributes()]]中的属性的属性值,第二个参数用来指定不返回的属性值
     * @param array $names list of attributes whose value needs to be returned.
     * Defaults to null, meaning all attributes listed in [[attributes()]] will be returned.
     * If it is an array, only the attributes in the array will be returned.
     * @param array $except list of attributes whose value should NOT be returned.
     * @return array attribute values (name => value).
     */
    public function getAttributes($names = null, $except = [])
    {
        $values = [];
        if ($names === null) {
            //属性名为空,则返回所有[[attributes()]]中的属性的属性值
            $names = $this->attributes();
        }
        foreach ($names as $name) {
            //指定属性名(数组格式),遍历返回属性值
            $values[$name] = $this->$name;
        }
        foreach ($except as $name) {
            //如果指定排除的属性值,则注销该属性值
            unset($values[$name]);
        }

        return $values;
    }

    /**
     * Sets the attribute values in a massive way.
     * 批量设置属性值
     * @param array $values attribute values (name => value) to be assigned to the model.
     * @param boolean $safeOnly whether the assignments should only be done to the safe attributes.
     * A safe attribute is one that is associated with a validation rule in the current [[scenario]].
     * @see safeAttributes()
     * @see attributes()
     */
    public function setAttributes($values, $safeOnly = true)
    {
        // 判断传入的属性值是否为数组
        if (is_array($values)) {
            // array_flip — 交换数组中的键和值
            // 将属性放到了 key 上
            // 默认取 safeAttributes 中的属性
            $attributes = array_flip($safeOnly ? $this->safeAttributes() : $this->attributes());
            foreach ($values as $name => $value) {
                if (isset($attributes[$name])) {
                    // 如果存在该属性,就直接赋值
                    $this->$name = $value;
                } elseif ($safeOnly) {
                    // 如果不存在,而且是 safeOnly 的话,就触发一下 onUnsafeAttribute 方法
                    $this->onUnsafeAttribute($name, $value);
                }
            }
        }
    }

    /**
     * This method is invoked when an unsafe attribute is being massively assigned.
     * 该方法在一个unsafe属性被批量赋值时被调用,如果是调试状态,就写入log 记录下没有成功设置的不安全的属性
     * The default implementation will log a warning message if YII_DEBUG is on.
     * It does nothing otherwise.
     * @param string $name the unsafe attribute name
     * @param mixed $value the attribute value
     */
    public function onUnsafeAttribute($name, $value)
    {
        if (YII_DEBUG) {
            // 如果是调试状态,就写入log 记录下没有成功设置的不安全的属性
            Yii::trace("Failed to set unsafe attribute '$name' in '" . get_class($this) . "'.", __METHOD__);
        }
    }

    /**
     * Returns the scenario that this model is used in.
     * 获取当前模型的使用场景
     *
     * Scenario affects how validation is performed and which attributes can
     * be massively assigned.
     * 场景可以影响批量赋值属性的验证
     *
     * @return string the scenario that this model is in. Defaults to [[SCENARIO_DEFAULT]].
     */
    public function getScenario()
    {
        // 获取当前的场景
        return $this->_scenario;
    }

    /**
     * Sets the scenario for the model.
     * Note that this method does not check if the scenario exists or not.
     * The method [[validate()]] will perform this check.
     * @param string $value the scenario that this model is in.
     */
    public function setScenario($value)
    {
        // 设置当前的场景
        $this->_scenario = $value;
    }

    /**
     * Returns the attribute names that are safe to be massively assigned in the current scenario.
     * 批量返回当前场景中安全的属性名
     * @return string[] safe attribute names
     */
    public function safeAttributes()
    {
        // 获取当前的场景
        $scenario = $this->getScenario();
        // 获取所有场景及其属性
        $scenarios = $this->scenarios();
        if (!isset($scenarios[$scenario])) {
            // 场景不存在,就返回空
            return [];
        }
        $attributes = [];
        foreach ($scenarios[$scenario] as $attribute) {
            // 将开头不是!的属性才会放入到 safeAttributes 中, 即以!开头的属性不会被放到 safeAttributes 中
            if ($attribute[0] !== '!') {
                $attributes[] = $attribute;
            }
        }

        return $attributes;
    }

    /**
     * Returns the attribute names that are subject to validation in the current scenario.
     * 返回在默认场景中验证的属性名
     * @return string[] safe attribute names
     */
    public function activeAttributes()
    {
        // 获取当前的场景
        $scenario = $this->getScenario();
        // 获取所有场景及其属性
        $scenarios = $this->scenarios();
        if (!isset($scenarios[$scenario])) {
            return [];
        }
        $attributes = $scenarios[$scenario];
        foreach ($attributes as $i => $attribute) {
            // 如果属性名以!开头,就把!截取掉
            // !开头的属性来自rules,加!能够使规则(即 validator)生效,但却能够不出现在 safeAttributes 中
            if ($attribute[0] === '!') {
                $attributes[$i] = substr($attribute, 1);
            }
        }

        return $attributes;
    }

    /**
     * Populates the model with input data.
     * 用输入的数据填充模型
     * This method provides a convenient shortcut for:
     * 该方法提供了一个方便快捷的方式:
     *
     * ```php
     * if (isset($_POST['FormName'])) {
     *     $model->attributes = $_POST['FormName'];
     *     if ($model->save()) {
     *         // handle success
     *     }
     * }
     * ```
     *
     * which, with `load()` can be written as:
     *
     * ```php
     * if ($model->load($_POST) && $model->save()) {
     *     // handle success
     * }
     * ```
     *
     * `load()` gets the `'FormName'` from the model's [[formName()]] method (which you may override), unless the
     * `$formName` parameter is given. If the form name is empty, `load()` populates the model with the whole of `$data`,
     * instead of `$data['FormName']`.
     *
     * Note, that the data being populated is subject to the safety check by [[setAttributes()]].
     *
     * @param array $data the data array to load, typically `$_POST` or `$_GET`.
     * @param string $formName the form name to use to load the data into the model.
     * If not set, [[formName()]] is used.
     * @return boolean whether `load()` found the expected form in `$data`.
     */
    public function load($data, $formName = null)
    {
        // 如果存在 yii 的 form,就使用该 form,否则就取所在类的名称(不含 namespace)
        $scope = $formName === null ? $this->formName() : $formName;
        if ($scope === '' && !empty($data)) {
            // 如果 $scope 为空字符串,且 $data不为空,就设置属性,即创建
            $this->setAttributes($data);

            return true;
        } elseif (isset($data[$scope])) {
            // 否则,必须存在 $data[$scope],使用 $data[$scope] 去设置属性
            $this->setAttributes($data[$scope]);

            return true;
        } else {
            return false;
        }
    }

    /**
     * Populates a set of models with the data from end user.
     * 加载数据到所在的 model 的集合中
     * This method is mainly used to collect tabular data input.
     * 此方法主要用于收集表格数据输入
     * The data to be loaded for each model is `$data[formName][index]`, where `formName`
     * refers to the value of [[formName()]], and `index` the index of the model in the `$models` array.
     * If [[formName()]] is empty, `$data[index]` will be used to populate each model.
     * The data being populated to each model is subject to the safety check by [[setAttributes()]].
     * @param array $models the models to be populated. Note that all models should have the same class.
     * @param array $data the data array. This is usually `$_POST` or `$_GET`, but can also be any valid array
     * supplied by end user.
     * @param string $formName the form name to be used for loading the data into the models.
     * If not set, it will use the [[formName()]] value of the first model in `$models`.
     * This parameter is available since version 2.0.1.
     * @return boolean whether at least one of the models is successfully populated.
     */
    public static function loadMultiple($models, $data, $formName = null)
    {
        if ($formName === null) {
            //表名为空
            // reset — 将数组的内部指针指向第一个单元
            $first = reset($models);
            if ($first === false) {
                // $models不存在就返回 false
                return false;
            }
            // 取得所在类的名称(不含 namespace)
            $formName = $first->formName();
        }

        $success = false;
        // 遍历 $models,一个个加载数据
        foreach ($models as $i => $model) {

            if ($formName == '') {
                if (!empty($data[$i])) {
                    // 数据不为空,就 load 到相应的 model 中
                    $model->load($data[$i], '');
                    $success = true;
                }
            } elseif (!empty($data[$formName][$i])) {
                // 存在 $formName,且数据不为空,就 load 到相应的 model 中
                $model->load($data[$formName][$i], '');
                $success = true;
            }
        }

        return $success;
    }

    /**
     * Validates multiple models.
     * 验证多个模型
     * This method will validate every model. The models being validated may
     * be of the same or different types.
     * @param array $models the models to be validated
     * @param array $attributeNames list of attribute names that should be validated.
     * If this parameter is empty, it means any attribute listed in the applicable
     * validation rules should be validated.
     * @return boolean whether all models are valid. False will be returned if one
     * or multiple models have validation error.
     */
    public static function validateMultiple($models, $attributeNames = null)
    {
        $valid = true;
        /* @var $model Model */
        foreach ($models as $model) {
            //遍历$models 调用validate()方法
            $valid = $model->validate($attributeNames) && $valid;
        }

        return $valid;
    }

    /**
     * Returns the list of fields that should be returned by default by [[toArray()]] when no specific fields are specified.
     * 以数组形式返回一个字段名或字段定义
     * A field is a named element in the returned array by [[toArray()]].
     *
     * This method should return an array of field names or field definitions.
     * 此方法应该返回一个字段名或字段定义的数组
     * If the former, the field name will be treated as an object property name whose value will be used
     * as the field value. If the latter, the array key should be the field name while the array value should be
     * 如果前者,该字段名将被视为一个对象属性名,其值将用作该字段值。
     * the corresponding field definition which can be either an object property name or a PHP callable
     * 如果是后者,数组的键应该是字段名称,数组的值应相应的字段定义可以是一个对象的属性名称或PHP回调函数
     * returning the corresponding field value. The signature of the callable should be:
     *
     * ```php
     * function ($model, $field) {
     *     // return field value
     * }
     * ```
     *
     * For example, the following code declares four fields:
     *
     * - `email`: the field name is the same as the property name `email`;
     * - `firstName` and `lastName`: the field names are `firstName` and `lastName`, and their
     *   values are obtained from the `first_name` and `last_name` properties;
     * - `fullName`: the field name is `fullName`. Its value is obtained by concatenating `first_name`
     *   and `last_name`.
     *
     * ```php
     * return [
     *     'email',
     *     'firstName' => 'first_name',
     *     'lastName' => 'last_name',
     *     'fullName' => function ($model) {
     *         return $model->first_name . ' ' . $model->last_name;
     *     },
     * ];
     * ```
     *
     * In this method, you may also want to return different lists of fields based on some context
     * information. For example, depending on [[scenario]] or the privilege of the current application user,
     * you may return different sets of visible fields or filter out some fields.
     * 在这个方法中,可能还希望在根据条件返回不同的字段列表,例如,根据[[scenario]]或者当前应用程序用户的权限
     * 设置不同的可见字段或者过滤某些字段
     *
     * The default implementation of this method returns [[attributes()]] indexed by the same attribute names.
     * 默认返回[[attributes()]]中的属性名为索引的所有字段
     * @return array the list of field names or field definitions.
     * @see toArray()
     */
    public function fields()
    {
        $fields = $this->attributes();
        // array_combine — 创建一个数组,用一个数组的值作为其键名,另一个数组的值作为其值
        return array_combine($fields, $fields);
    }

    /**
     * Returns an iterator for traversing the attributes in the model.
     * 返回模型中一个遍历属性的迭代器
     * This method is required by the interface [[\IteratorAggregate]].
     * @return ArrayIterator an iterator for traversing the items in the list.
     */
    public function getIterator()
    {
        // 获取该 model 的所有属性
        $attributes = $this->getAttributes();
        // ArrayIterator 这个迭代器允许在遍历数组和对象时删除和更新值与键
        // 当你想多次遍历相同数组时你需要实例化 ArrayObject,然后让这个实例创建一个 ArrayIteratror 实例, 然后使用 foreach 或者 手动调用 getIterator() 方法
        return new ArrayIterator($attributes);
    }

    /**
     * Returns whether there is an element at the specified offset.
     * This method is required by the SPL interface [[\ArrayAccess]].
     * It is implicitly called when you use something like `isset($model[$offset])`.
     * @param mixed $offset the offset to check on
     * @return boolean
     */
    public function offsetExists($offset)
    {
        // 将 isset($model[$offset]) 重写为 isset($model->$offset)
        return $this->$offset !== null;
    }

    /**
     * Returns the element at the specified offset.
     * 获取指定下标的元素
     * This method is required by the SPL interface [[\ArrayAccess]].
     * 该方法将[[\ArrayAccess]]接口中的数组访问模式改写为对象访问模式
     * It is implicitly called when you use something like `$value = $model[$offset];`.
     * @param mixed $offset the offset to retrieve element.
     * @return mixed the element at the offset, null if no element is found at the offset
     */
    public function offsetGet($offset)
    {
        // 将获取 $model[$offset] 重写为 $model->$offset
        return $this->$offset;
    }

    /**
     * Sets the element at the specified offset.
     * 设置指定下标的元素
     * This method is required by the SPL interface [[\ArrayAccess]].
     * 该方法将[[\ArrayAccess]]接口中的数组访问模式改写为对象访问模式
     * It is implicitly called when you use something like `$model[$offset] = $item;`.
     * @param integer $offset the offset to set element
     * @param mixed $item the element value
     */
    public function offsetSet($offset, $item)
    {
        // 将 $model[$offset] = $item 重写为 $model->$offset = $item
        $this->$offset = $item;
    }

    /**
     * Sets the element value at the specified offset to null.
     * 删除指定下标的元素
     * This method is required by the SPL interface [[\ArrayAccess]].
     * 该方法将[[\ArrayAccess]]接口中的数组访问模式改写为对象访问模式
     * It is implicitly called when you use something like `unset($model[$offset])`.
     * @param mixed $offset the offset to unset element
     */
    public function offsetUnset($offset)
    {
        // 将 unset($model[$offset]) 重写为 $model->$offset = null
        $this->$offset = null;
    }

Yii源码阅读笔记(十六)的更多相关文章

  1. Yii源码阅读笔记(六)

    组件(component),是Yii框架的基类,实现了属性.事件.行为三类功能,如果需要事件和行为的功能,需要继承该类,不需要可直接继承Object类: namespace yii\base; use ...

  2. Yii源码阅读笔记(一)

    今天开始阅读yii2的源码,想深入了解一下yii框架的工作原理,同时学习一下优秀的编码规范和风格.在此记录一下阅读中的小心得. 每个框架都有一个入口文件,首先从入口文件开始,yii2的入口文件位于we ...

  3. Mina源码阅读笔记(六)—Mina异步IO的实现IoFuture

    IoFuture是和IoSession紧密相连的一个类,在官网上并没有对它的描述,因为它一般不会显示的拿出来用,权当是一个工具类被session所使用.当然在作用上,这个系列可并不简单,我们先看源码的 ...

  4. 重新整理 .net core 实践篇——— 权限中间件源码阅读[四十六]

    前言 前面介绍了认证中间件,下面看一下授权中间件. 正文 app.UseAuthorization(); 授权中间件是这个,前面我们提及到认证中间件并不会让整个中间件停止. 认证中间件就两个作用,我们 ...

  5. Yii源码阅读笔记(二十六)

    Application 类中设置路径的方法和调用ServiceLocator(服务定位器)加载运行时的组件的方法注释: /** * Handles the specified request. * 处 ...

  6. Yii源码阅读笔记(三十五)

    Container,用于动态地创建.注入依赖单元,映射依赖关系等功能,减少了许多代码量,降低代码耦合程度,提高项目的可维护性. namespace yii\di; use ReflectionClas ...

  7. Yii源码阅读笔记(三十四)

    Instance类, 表示依赖注入容器或服务定位器中对某一个对象的引用 namespace yii\di; use Yii; use yii\base\InvalidConfigException; ...

  8. Yii源码阅读笔记(三十二)

    web/Application类的注释,继承base/Application类,针对web应用的一些处理: namespace yii\web; use Yii; use yii\base\Inval ...

  9. Yii源码阅读笔记(三十)

    Widget类是所有小部件的基类,开始,结束和渲染小部件内容的方法的注释: namespace yii\base; use Yii; use ReflectionClass; /** * Widget ...

随机推荐

  1. 菜鸟学SSH(十五)——简单模拟Hibernate实现原理

    之前写了Spring的实现原理,今天我们接着聊聊Hibernate的实现原理,这篇文章只是简单的模拟一下Hibernate的原理,主要是模拟了一下Hibernate的Session类.好了,废话不多说 ...

  2. jquery easy ui 1.3.4 内容组件(2)

    2.1.panel(面板) panel面板是easyui里面非常基础的一个内容组件,在我们后期学的tabs (选项卡).accordion(手风琴)这两种内容组件都依赖于panel组件.构建一个pan ...

  3. ytu 1041: 迭代法求平方根(水题)

    1041: 迭代法求平方根 Time Limit: 1 Sec  Memory Limit: 128 MBSubmit: 227  Solved: 146[Submit][Status][Web Bo ...

  4. [译]ASP.NET 性能监控

    概述:在性能测试中性能监视器是非常强大的工具,本文主要简述了几个关键的计数器和相关的阈值. 监控性能计数器 很多的性能计数器在性能调优中是非常重要的,由于性能计数器太多,很多人不知道选择那些计数器. ...

  5. https_request

    <?php $access_token = );         curl_setopt($curl, CURLOPT_POSTFIELDS, $data);     }     curl_se ...

  6. vijos p1002 dp ***

    链接:点我 一开始的方程式很好写的,但是数据太大,考虑到石子数目很小,我们对其进行离散化,若相邻两点距离超过ya的值,则后面所有点都往前移动,这里ya的值是可以调整的 #include <ios ...

  7. poj 2186 有向图强连通分量

    奶牛互相之间有爱慕关系,找到被其它奶牛都喜欢的奶牛的数目 用tarjan缩点,然后判断有向图中出度为0的联通分量的个数,如果为1就输出联通分量中的点的数目,否则输出0. 算法源自kb模板 #inclu ...

  8. Sonar+Hudson+Maven构建系列之三:安装Hudson

    摘要:其实前面介绍过Sonar,后面Hudson安装就方便了.安装Hudson之前说说Hudson相关的事,现在世面上的有两种与Hudson相关的CI工具,一个是Hudson,一个是Jenkins,这 ...

  9. AndroidManifest.xml相关知识

    AndroidManifest.xml <?xml version="1.0" encoding="utf-8"?> <manifest  ...

  10. Android 启动APP时黑屏白屏的三个解决方案

    你会很奇怪,为什么有些app启动时,会出现一会儿的黑屏或者白屏才进入Activity的界面显示,但是有些app却不会如QQ手机端,的确这里要做处理一下.这里先了解一下为什么会出现这样的现象,其实很简单 ...