yii2框架随笔37

vendor/yiisoft/yii2/base/Event.php

<?php

namespace yiibase;

 //事件是所有事件类的基类。它封装了参数与事件相关联。
 //如果一个事件处理程序集[[进行]]是真的,其余的,uninvoked处理程序将不再被称为处理事件。
 //另外,添加一个事件处理程序时,额外的数据可能被传递和可以通过[[数据]]属性调用事件处理程序时。
class Event extends Object
{
    /**
     * @var string the event name. This property is set by [[Component::trigger()]] and [[trigger()]].
     * Event handlers may use this property to check what event it is handling.
     * 事件的名字
     */
    public $name;
    /**
     * @var object the sender of this event. If not set, this property will be
     * set as the object whose "trigger()" method is called.
     * This property may also be a `null` when this event is a
     * class-level event which is triggered in a static context.
     * 触发事件的对象
     */
    public $sender;
    /**
     * @var boolean whether the event is handled. Defaults to false.
     * When a handler sets this to be true, the event processing will stop and
     * ignore the rest of the uninvoked event handlers.
     * 记录事件是否已被处理,当 handled 被设置为 true 时,执行到这个 event 的时候,会停止,并忽略剩下的 event
     */
    public $handled = false;

    public $data;    
     // 存储所有的 event,因为是 static 的属性,所有的 event 对象/类都共享这一份数据
     
    private static $_events = [];


     //附加一个事件处理程序来一个类级别的事件,当一个类级别事件触发、事件处理程序,该类将调用父类
     //为一个类添加事件

    public static function on($class, $name, $handler, $data = null, $append = true)
    {
        // 去掉 class 最左边的斜杠
        $class = ltrim($class, '\');
        // 如果 append 为true,就放到 $_events 中名字为 $name 的数组的最后,否则放到最前面
        if ($append || empty(self::$_events[$name][$class])) {
            self::$_events[$name][$class][] = [$handler, $data];
        } else {
            array_unshift(self::$_events[$name][$class], [$handler, $data]);
        }
    }


    //移除一个类的事件

    public static function off($class, $name, $handler = null)
    {
        $class = ltrim($class, '\');
        if (empty(self::$_events[$name][$class])) {
            // 不存在该事件
            return false;
        }
        if ($handler === null) {
            // 如果 handler 为空,直接将在该类下该事件移除,即移出所有的是这个名字的事件
            unset(self::$_events[$name][$class]);
            return true;
        } else {
            $removed = false;
            // 如果 $handler 不为空,循环 $_events 找到相应的 handler,只移除这个 handler 和 data 组成的数组
            foreach (self::$_events[$name][$class] as $i => $event) {
                if ($event[0] === $handler) {
                    unset(self::$_events[$name][$class][$i]);
                    $removed = true;
                }
            }
            if ($removed) {
                // 移除之后,使数组重新变成一个自然数组
                self::$_events[$name][$class] = array_values(self::$_events[$name][$class]);
            }

            return $removed;
        }
    }

    /**
     * Returns a value indicating whether there is any handler attached to the specified class-level event.
     * Note that this method will also check all parent classes to see if there is any handler attached
     * to the named event.
     * 检测在某个类或者对象是否具有某个事件
     * @param string|object $class the object or the fully qualified class name specifying the class-level event.
     * @param string $name the event name.
     * @return boolean whether there is any handler attached to the event.
     */
    public static function hasHandlers($class, $name)
    {
        if (empty(self::$_events[$name])) {
            // 不存在,直接返回
            return false;
        }
        if (is_object($class)) {
            // 如果是一个 object,就获取其类名
            $class = get_class($class);
        } else {
            // 如果是一个类名,就去掉 class 最左边的斜杠
            $class = ltrim($class, '\');
        }
        // 如果该类中找不到,就去父类中找,直到找到或者没有父类了为止
        do {
            if (!empty(self::$_events[$name][$class])) {
                return true;
            }
        } while (($class = get_parent_class($class)) !== false);

        return false;
    }

    /**
     * Triggers a class-level event.
     * This method will cause invocation of event handlers that are attached to the named event
     * for the specified class and all its parent classes.
     * 触发某个类或者对象的某个事件
     * @param string|object $class the object or the fully qualified class name specifying the class-level event.
     * @param string $name the event name.
     * @param Event $event the event parameter. If not set, a default [[Event]] object will be created.
     */
    public static function trigger($class, $name, $event = null)
    {
        if (empty(self::$_events[$name])) {
            return;
        }
        if ($event === null) {
            // 事件不存在,就创建一个 Event 对象
            $event = new static;
        }
        // 设置event对象的属性,默认是未被处理的
        $event->handled = false;
        $event->name = $name;

        if (is_object($class)) {
            if ($event->sender === null) {
                // 如果 $class 是个对象,并且是 sender 为空,就将 $class 赋给 sender,即 $class 就是触发事件的对象
                $event->sender = $class;
            }
            $class = get_class($class);
        } else {
            $class = ltrim($class, '\');
        }
        // 循环类的 $_event,直到遇到 $event->handled 为真或者没有父类了为止
        do {
            if (!empty(self::$_events[$name][$class])) {
                foreach (self::$_events[$name][$class] as $handler) {
                    // 将参数赋到 event 对象的 data 属性上
                    $event->data = $handler[1];
                    // 调用 $handler 方法
                    // 在方法中,可以用 $this->data 取到相应的参数
                    // 也可以在其中设置 $this->handled 的值,中断后续事件的触发
                    call_user_func($handler[0], $event);
                    // 当某个 handled 被设置为 true 时,执行到这个事件的时候,会停止,并忽略剩下的事件
                    if ($event->handled) {
                        return;
                    }
                }
            }
        } while (($class = get_parent_class($class)) !== false);
    }
}
<?php

namespace yiibase;

 //事件是所有事件类的基类。它封装了参数与事件相关联。
 //如果一个事件处理程序集[[进行]]是真的,其余的,uninvoked处理程序将不再被称为处理事件。
 //另外,添加一个事件处理程序时,额外的数据可能被传递和可以通过[[数据]]属性调用事件处理程序时。
class Event extends Object
{
    /**
     * @var string the event name. This property is set by [[Component::trigger()]] and [[trigger()]].
     * Event handlers may use this property to check what event it is handling.
     * 事件的名字
     */
    public $name;
    /**
     * @var object the sender of this event. If not set, this property will be
     * set as the object whose "trigger()" method is called.
     * This property may also be a `null` when this event is a
     * class-level event which is triggered in a static context.
     * 触发事件的对象
     */
    public $sender;
    /**
     * @var boolean whether the event is handled. Defaults to false.
     * When a handler sets this to be true, the event processing will stop and
     * ignore the rest of the uninvoked event handlers.
     * 记录事件是否已被处理,当 handled 被设置为 true 时,执行到这个 event 的时候,会停止,并忽略剩下的 event
     */
    public $handled = false;

    public $data;    
     // 存储所有的 event,因为是 static 的属性,所有的 event 对象/类都共享这一份数据
     
    private static $_events = [];


     //附加一个事件处理程序来一个类级别的事件,当一个类级别事件触发、事件处理程序,该类将调用父类
     //为一个类添加事件

    public static function on($class, $name, $handler, $data = null, $append = true)
    {
        // 去掉 class 最左边的斜杠
        $class = ltrim($class, '\');
        // 如果 append 为true,就放到 $_events 中名字为 $name 的数组的最后,否则放到最前面
        if ($append || empty(self::$_events[$name][$class])) {
            self::$_events[$name][$class][] = [$handler, $data];
        } else {
            array_unshift(self::$_events[$name][$class], [$handler, $data]);
        }
    }


    //移除一个类的事件

    public static function off($class, $name, $handler = null)
    {
        $class = ltrim($class, '\');
        if (empty(self::$_events[$name][$class])) {
            // 不存在该事件
            return false;
        }
        if ($handler === null) {
            // 如果 handler 为空,直接将在该类下该事件移除,即移出所有的是这个名字的事件
            unset(self::$_events[$name][$class]);
            return true;
        } else {
            $removed = false;
            // 如果 $handler 不为空,循环 $_events 找到相应的 handler,只移除这个 handler 和 data 组成的数组
            foreach (self::$_events[$name][$class] as $i => $event) {
                if ($event[0] === $handler) {
                    unset(self::$_events[$name][$class][$i]);
                    $removed = true;
                }
            }
            if ($removed) {
                // 移除之后,使数组重新变成一个自然数组
                self::$_events[$name][$class] = array_values(self::$_events[$name][$class]);
            }

            return $removed;
        }
    }

    /**
     * Returns a value indicating whether there is any handler attached to the specified class-level event.
     * Note that this method will also check all parent classes to see if there is any handler attached
     * to the named event.
     * 检测在某个类或者对象是否具有某个事件
     * @param string|object $class the object or the fully qualified class name specifying the class-level event.
     * @param string $name the event name.
     * @return boolean whether there is any handler attached to the event.
     */
    public static function hasHandlers($class, $name)
    {
        if (empty(self::$_events[$name])) {
            // 不存在,直接返回
            return false;
        }
        if (is_object($class)) {
            // 如果是一个 object,就获取其类名
            $class = get_class($class);
        } else {
            // 如果是一个类名,就去掉 class 最左边的斜杠
            $class = ltrim($class, '\');
        }
        // 如果该类中找不到,就去父类中找,直到找到或者没有父类了为止
        do {
            if (!empty(self::$_events[$name][$class])) {
                return true;
            }
        } while (($class = get_parent_class($class)) !== false);

        return false;
    }

    /**
     * Triggers a class-level event.
     * This method will cause invocation of event handlers that are attached to the named event
     * for the specified class and all its parent classes.
     * 触发某个类或者对象的某个事件
     * @param string|object $class the object or the fully qualified class name specifying the class-level event.
     * @param string $name the event name.
     * @param Event $event the event parameter. If not set, a default [[Event]] object will be created.
     */
    public static function trigger($class, $name, $event = null)
    {
        if (empty(self::$_events[$name])) {
            return;
        }
        if ($event === null) {
            // 事件不存在,就创建一个 Event 对象
            $event = new static;
        }
        // 设置event对象的属性,默认是未被处理的
        $event->handled = false;
        $event->name = $name;

        if (is_object($class)) {
            if ($event->sender === null) {
                // 如果 $class 是个对象,并且是 sender 为空,就将 $class 赋给 sender,即 $class 就是触发事件的对象
                $event->sender = $class;
            }
            $class = get_class($class);
        } else {
            $class = ltrim($class, '\');
        }
        // 循环类的 $_event,直到遇到 $event->handled 为真或者没有父类了为止
        do {
            if (!empty(self::$_events[$name][$class])) {
                foreach (self::$_events[$name][$class] as $handler) {
                    // 将参数赋到 event 对象的 data 属性上
                    $event->data = $handler[1];
                    // 调用 $handler 方法
                    // 在方法中,可以用 $this->data 取到相应的参数
                    // 也可以在其中设置 $this->handled 的值,中断后续事件的触发
                    call_user_func($handler[0], $event);
                    // 当某个 handled 被设置为 true 时,执行到这个事件的时候,会停止,并忽略剩下的事件
                    if ($event->handled) {
                        return;
                    }
                }
            }
        } while (($class = get_parent_class($class)) !== false);
    }
}

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 yiibase;

use Yii;
use yiihelpersArrayHelper;
use yiiwebLink;
use yiiwebLinkable;

   
   //traits 是一种为类似 PHP 的单继承语言而准备的代码复用机制。
   //trait 为了减少单继承语言的限制,使开发人员能够自由地在不同层次结构内独立的类中复用方法集。
   //traits 和类组合的语义是定义了一种方式来减少复杂性,避免传统多继承和混入类(Mixin)相关的典型问题。
   //trait 如果要在 Class 中使用该 Trait,那么使用 use 关键字
trait ArrayableTrait
{
    
    /**
     * 返回的字段列表应该返回默认的[[toArray()]]当没有指定特定的字段。
     *
     * 一个字段是一个名叫返回的数组元素的[[toArray()]]
     *
     * *此方法应该返回一个数组字段名和字段定义
     * 如果是后者,数组键应该字段名,而数组值应该*对应的字段定义可以是一个对象的属性名或一个PHP调用*返回相应的字段值
     * 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
     * returning the corresponding field value. The signature of the callable should be:
     * @see toArray()
     */
    public function fields()
    {
        // 获取该对象的 public 成员变量的名列表,赋给 $fields
        $fields = array_keys(Yii::getObjectVars($this));
        // array_combine — 创建一个数组,用一个数组的值作为其键名,另一个数组的值作为其值
        // 返回数组, keys 和 values 都是 $fields
        return array_combine($fields, $fields);
    }

   //返回字段的列表,可以进一步扩大,返回的[[toArray()]]。
   //这种方法类似于[[字段()]]除了返回的字段列表。 
    public function extraFields()
    {
        return [];
    }
    //将模型转换为一个数组。
    //该方法首先确定哪些字段被包括在生成的数组通过调用[[resolveFields()]]。
    //它将把这些字段的模型转换为一个数组。如果美元递归的是真的,  
    //任何嵌入对象也将转化为数组  
    //如果模型实现了[[链接]]接口,生成的数组也会“_link”元素 
    //指一个链接列表所指定的接口

    public function toArray(array $fields = [], array $expand = [], $recursive = true)
    {
        $data = [];
        foreach ($this->resolveFields($fields, $expand) as $field => $definition) {
            // 如果是 string, 就返回当前对象的该属性, 否则调用 call_user_func 去执行 $definition 函数
            $data[$field] = is_string($definition) ? $this->$definition : call_user_func($definition, $this, $field);
        }

        if ($this instanceof Linkable) {
            $data['_links'] = Link::serialize($this->getLinks());
        }

        return $recursive ? ArrayHelper::toArray($data) : $data;
    }

    /**
     * Determines which fields can be returned by [[toArray()]].
     * 决定哪些 fields 会通过 toArray() 返回
     * This method will check the requested fields against those declared in [[fields()]] and [[extraFields()]]
     * to determine which fields can be returned.
     * @param array $fields the fields being requested for exporting
     * @param array $expand the additional fields being requested for exporting
     * @return array the list of fields to be exported. The array keys are the field names, and the array values
     * are the corresponding object property names or PHP callables returning the field values.
     */
    protected function resolveFields(array $fields, array $expand)
    {
        $result = [];

        // 循环 $this->fields() 中取得的 fields
        foreach ($this->fields() as $field => $definition) {
            if (is_integer($field)) {
                // 如果 $field 是 int, 就将 $definition 赋值给 $field
                $field = $definition;
            }
            if (empty($fields) || in_array($field, $fields, true)) {
                // 如果 $fields 为空, 或者 $field 在 $fields 中, 就将 $definition 赋到 $result 中
                // 即 $fields 为空,就将所有的对象的属性都放入到结果中
                // 不为空时,如果当前对象的属性在 $fields 中存在, 就将对象中定义的该属性的值放入到结果中
                $result[$field] = $definition;
            }
        }

        if (empty($expand)) {
            return $result;
        }

        // 循环 $this->extraFields() 中取得的 fields
        foreach ($this->extraFields() as $field => $definition) {
            if (is_integer($field)) {
                // 如果 $field 是 int, 就将 $definition 赋值给 $field
                $field = $definition;
            }
            if (in_array($field, $expand, true)) {
                // 如果$field 在 $expand 中, 就将 $definition 赋到 $result 中
                // 即当前对象的扩展属性在 $fields 中存在, 就将对象中定义的该扩展属性的值放入到结果中
                $result[$field] = $definition;
            }
        }

        return $result;
    }
}
原文地址:https://www.cnblogs.com/taokai/p/5539273.html