Yii2的深入学习--yii\base\Event 类

根据之前一篇文章,我们知道 Yii2 的事件分两类,一是类级别的事件,二是实例级别的事件。类级别的事件是基于 yii\base\Event 实现,实例级别的事件是基于 yii\base\Component 实现。

今天先来看下类级别事件的实现,代码是 yii\base\Event 类。

<?php
namespace yii\base;

/**
 * Event is the base class for all event classes.
 */
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;
    /**
     * @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.
     */
    public $data;

    /**
     * 存储所有的 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:
     *
     * ~~~
     * 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.
     *
     * 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]].
     * @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.
     * @see off()
     */
    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]);
        }
    }

    /**
     * Detaches an event handler from a class-level event.
     *
     * This method is the opposite of [[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.
     * 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;
        }
        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);
    }
}

通过上面代码可以看出,类级别的 Event,其本质就是在 Event 类中的 $_events 变量中存储事件,触发事件的时候,只需将其取出,执行即可。

$_events里面的数据结构大概如下:

[
    ‘add‘ => [
        ‘Child‘ => [
            [function ($event) { ... }, $data],
            [[$object, ‘handleAdd‘], null],
            [[‘ChildClass‘, ‘handleAdd‘], $data],
            [‘handleAdd‘, $data]
        ],
        ‘ChildClass‘ => [
            ...
        ]
    ],
    ‘delete‘ => [
        ...
    ]
]

之后讲到yii\base\Component类时,我们会再来说一下实例级别的事件。

对 Yii2 源码有兴趣的同学可以关注项目 yii2-2.0.3-annotated,现在在上面已经添加了不少关于 Yii2 源码的注释,之后还会继续添加~

有兴趣的同学也可以参与进来,提交 Yii2 源码的注释。

时间: 2024-08-07 05:54:15

Yii2的深入学习--yii\base\Event 类的相关文章

Yii2的深入学习--yii\base\Object 类

之前我们说过 Yii2 中大多数类都继承自 yii\base\Object,今天就让我们来看一下这个类. Object 是一个基础类,实现了属性的功能,其基本内容如下: <?php namespace yii\base; use Yii; /** * Object 是一个基础类,实现了属性的功能 * Yii最基础的类,大多数类都继承了该类 */ class Object implements Configurable { /** * 获取静态方法调用的类名.返回类的名称,如果不是在类中调用则返回

Yii2的深入学习--事件

我们先来看下事件在 Yii2 中的使用,如下内容摘自 Yii2中文文档 事件可以将自定义代码“注入”到现有代码中的特定执行点.附加自定义代码到某个事件,当这个事件被触发时,这些代码就会自动执行.例如,邮件程序对象成功发出消息时可触发 messageSent 事件.如想追踪成功发送的消息,可以附加相应追踪代码到 messageSent 事件. Yii 引入了名为 [[yii\base\Component]] 的基类以支持事件.如果一个类需要触发事件就应该继承 [[yii\base\Componen

Yii2的深入学习--继承关系

想要了解 Yii2 的话,一定要对 Yii2 中向相关类的继承关系有所了解.由于暂时读的代码有限,下面的图中只列出了部分继承关系,之后回跟着源码阅读的越来越多而增加 由上图可以看到 Yii2 中大多数类都继承自 yii\base\Object,实现了属性的功能. yii\base\Component yii\base\Event 和 yii\base\Behavior 都继承了 yii\base\Object,yii\base\Component 是一个实现了属性/事件和行为功能的基础类,yii

Yii2的深入学习--自动加载机制

Yii2 的自动加载分两部分,一部分是 Composer 的自动加载机制,另一部分是 Yii2 框架自身的自动加载机制. Composer自动加载 对于库的自动加载信息,Composer 生成了一个 vendor/autoload.php 文件.你可以简单的引入这个文件,你会得到一个自动加载的支持. 在之前的文章,入口文件的介绍中,我们可以看到如下内容: // 引入 vendor 中的 autoload.php 文件,会基于 composer 的机制自动加载类 require(__DIR__ .

Yii2的深入学习--自动加载机制(转)

Yii2 的自动加载分两部分,一部分是 Composer 的自动加载机制,另一部分是 Yii2 框架自身的自动加载机制. Composer自动加载 对于库的自动加载信息,Composer 生成了一个 vendor/autoload.php 文件.你可以简单的引入这个文件,你会得到一个自动加载的支持. 在之前的文章,入口文件的介绍中,我们可以看到如下内容: // 引入 vendor 中的 autoload.php 文件,会基于 composer 的机制自动加载类 require(__DIR__ .

yii2学习——事件(event)

最近在学习Yii2,这里记录一下学习yii2的事件,一个简单的事件实例: 包括了一个对象.一个静态对象.一个匿名函数. app\controllers\siteController /**      * 事件处理      */     public function actionEvent(){         echo '这是事件处理<br/>';                  $person = new Person();                  $this->on(

安装yii2时出错 Invalid Parameter – yii\base\InvalidParamException

最近composer安装yii2的时候页面报了这个错,应该是bower的前端资源位置改变的缘故! Invalid Parameter – yii\base\InvalidParamException The file or directory to be published does not exist:/var/www/yii/vendor/bower/jquery/dist 解决方法1: 将目录:  vendor/bower-asset 改为: vendor/bower 当然这个方法不能根本

yii2.0中yii\base\Application的一些属性

必要属性 yii\base\Application::id 区分其他应用的唯一标识ID yii\base\Application::basePath 该应用的根目录 其他属性 yii\base\Application::aliases 定义多个别名,通常是方便路径,namespace的访问. yii\base\Application::bootstrap 指定应用启动阶段需要运行的组件. yii\web\Application::catchAll 指定一个要处理所有用户请求的 控制器方法,通常在

yii2源码学习笔记(六)

Behvaior类,Behavior类是所有事件类的基类: 目录yii2\base\Behavior.php 1 <?php 2 /** 3 * @link http://www.yiiframework.com/ 4 * @copyright Copyright (c) 2008 Yii Software LLC 5 * @license http://www.yiiframework.com/license/ 6 */ 7 8 namespace yii\base; 9 10 /** 11