码迷,mamicode.com
首页 > 其他好文 > 详细

Yii源码阅读笔记(十六)

时间:2016-04-25 06:32:59      阅读:157      评论:0      收藏:0      [点我收藏+]

标签:

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源码阅读笔记(十六)

标签:

原文地址:http://www.cnblogs.com/isleep/p/5429069.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!