<?php
/**
 * @link http://www.yiiframework.com/
 * @copyright Copyright (c) 2008 Yii Software LLC
 * @license http://www.yiiframework.com/license/
 */

namespace yii\base;

/**
 * Event is the base class for all event classes.
 *
 * It encapsulates the parameters associated with an event.
 * The [[sender]] property describes who raises the event.
 * And the [[handled]] property indicates if the event is handled.
 * If an event handler sets [[handled]] to be `true`, the rest of the
 * uninvoked handlers will no longer be called to handle the event.
 *  Event是所有事件类的基类。 它封装了与事件相关的参数。 sender属性指的是谁发起来的事件。
 *  handled属性指的是事件的处理方式. 如果一个事件处理程序设置了handled为true,其它未处理的事件处理程序将不会被调用。
 *
 * Additionally, when attaching an event handler, extra data may be passed
 * and be available via the [[data]] property when the event handler is invoked.
 * 当附加事件处理程序时,可能会通过额外的数据 ,当事件处理程序被调用时,可通过[ data]属性提供。
 * @author Qiang Xue <qiang.xue@gmail.com>
 * @since 2.0
 */
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.
     *
     * 事件的名字,通过[[Component::trigger()]] 和 [[trigger()]]方法设置,事件处理程序可以使用此属性来检查它的处理事件。
     */
    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.
     *
     * 触发事件的对象,如果未设置,则设置为调用"trigger()"方法的对象,如果是在静态环境下触发的类级别的事件,属性为空
     */
    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;
    /**
     * @var mixed the data that is passed to [[Component::on()]] when attaching an event handler.
     * Note that this varies according to which event handler is currently executing.
     *
     * 附加一个事件处理程序时通过[[Component::on()]]传入data,且对应当前执行的事件处理程序
     */
    public $data;

    /**
     * @var array contains all globally registered event handlers.
     *
     * 存储所有的 event,因为是 static 的属性,所有的 event 对象/类都共享这一份数据
     */
    private static $_events = [];


    /**
     * Attaches an event handler to a class-level event.
     * 为一个类添加事件
     *
     * When a class-level event is triggered, event handlers attached
     * to that class and all parent classes will be invoked.
     * 当一个类级别事件触发,将调用该类和所有父类的事件处理程序。
     *
     * For example, the following code attaches an event handler to `ActiveRecord`'s
     * `afterInsert` event:
     *
     * ```php
     * Event::on(ActiveRecord::className(), ActiveRecord::EVENT_AFTER_INSERT, function ($event) {
     *     Yii::trace(get_class($event->sender) . ' is inserted.');
     * });
     * ```
     *
     * The handler will be invoked for EVERY successful ActiveRecord insertion.
     * 该处理程序是将每一个成功的[[ActiveRecord]]插入调用。
     *
     * For more details about how to declare an event handler, please refer to [[Component::on()]].
     *
     * @param string $class the fully qualified class name to which the event handler needs to attach.定义的类级别的对象或者类名称.
     * @param string $name the event name.事件名
     * @param callable $handler the event handler. 事件处理程序
     * @param mixed $data the data to be passed to the event handler when the event is triggered. 当事件被触发时,将传递给事件处理程序的数据
     * When the event handler is invoked, this data can be accessed via [[Event::data]].
     * 当调用事件处理程序时,该数据可以通过[[Event::data]]传递
     * @param boolean $append whether to append new event handler to the end of the existing
     * handler list. If `false`, the new handler will be inserted at the beginning of the existing
     * handler list.是否将新事件处理程序附加到现有的处理程序列表的结尾。如果false,新的处理程序将被插入到现有的处理程序列表开头
     * @see off()
     */
    public static function on($class, $name, $handler, $data = null, $append = true)
    {
        $class = ltrim($class, '\\'); // 去掉 class 最左边的反斜杠
        if ($append || empty(self::$_events[$name][$class])) {
            //如果 append 为true,附加到$_events中名字为 $name 的数组结尾。
            self::$_events[$name][$class][] = [$handler, $data];
        } else {
            //如果false,被插入列表开头
            array_unshift(self::$_events[$name][$class], [$handler, $data]);
        }
    }

    /**
     * Detaches an event handler from a class-level event.
     *
     * This method is the opposite of [[on()]].
     * [[on()]]的反方法,移除一个类的事件
     *
     * @param string $class the fully qualified class name from which the event handler needs to be detached.
     * 定义类级别的对象或者类名称.
     * @param string $name the event name. 事件名
     * @param callable $handler the event handler to be removed. 事件处理程序,如果是null,移除所有相关事件
     * If it is `null`, all handlers attached to the named event will be removed.
     * @return boolean whether a handler is found and detached. 一个处理程序是否被发现且分离。
     * @see on()
     */
    public static function off($class, $name, $handler = null)
    {
        // 去掉最左边的反斜线
        $class = ltrim($class, '\\');
        if (empty(self::$_events[$name][$class])) {
            return false; // 该事件不存在,返回false
        }
        if ($handler === null) { // 如果 $handler 为空,该类下该所有是这个名字的事件移除,
            unset(self::$_events[$name][$class]);
            return true;
        } else {
            $removed = false; //移除标记
            foreach (self::$_events[$name][$class] as $i => $event) {
                // 如果 $handler 不为空,循环 $_events 找到相应的 $handler,只移除这个 $handler 和 data 组成的数组
                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;
        }
    }

    /**
     * Detaches all registered class-level event handlers.
     * 分离所有注册的类级事件处理程序。
     *
     * @see on()
     * @see off()
     * @since 2.0.10
     */
    public static function offAll()
    {
        self::$_events = [];
    }

    /**
     * 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])) { //如果不存在事件,返回false
            return false;
        }
        if (is_object($class)) { //如果是对象,获取类名
            $class = get_class($class);
        } else {//如果是类名,去掉左边的反斜杠
            $class = ltrim($class, '\\');
        }

        $classes = array_merge(
            [$class],
            class_parents($class, true), //class_parents — 返回指定类的父类。
            class_implements($class, true) //class_implements — 返回指定的类实现的所有接口。
        );
        // 如果类中找不到,就去父类中找,直到找到或者没有父类了为止,返回true
        foreach ($classes as $class) {
            if (!empty(self::$_events[$name][$class])) {
                return true;
            }
        }

        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->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, '\\'); //不是对象,去掉左边的反斜线
        }

        $classes = array_merge(
            [$class],
            class_parents($class, true),
            class_implements($class, true)
        );
    // 循环类的 $_event,直到遇到 $event->handled 为真或者没有父类了为止
        foreach ($classes as $class) {
            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);
                    //call_user_func — 把第一个参数作为回调函数调用
                    if ($event->handled) {
                        // 当某个 handled 被设置为 true 时,执行到这个事件的时候,会停止,并忽略剩下的事件
                        return;
                    }
                }
            }
        }
    }
}
Logo

开放原子开发者工作坊旨在鼓励更多人参与开源活动,与志同道合的开发者们相互交流开发经验、分享开发心得、获取前沿技术趋势。工作坊有多种形式的开发者活动,如meetup、训练营等,主打技术交流,干货满满,真诚地邀请各位开发者共同参与!

更多推荐