search
HomeBackend DevelopmentPHP TutorialIn-depth learning of Yii2--yiibaseEvent class

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

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

<span>php
namespace yii\base;

</span><span>/*</span><span>*
 * Event is the base class for all event classes.
 </span><span>*/</span><span>class</span> Event <span>extends</span><span>Object</span><span>{
    </span><span>/*</span><span>*
     * @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.
     * 事件的名字
     </span><span>*/</span><span>public</span><span>$name</span><span>;
    </span><span>/*</span><span>*
     * @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.
     * 触发事件的对象
     </span><span>*/</span><span>public</span><span>$sender</span><span>;
    </span><span>/*</span><span>*
     * @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
     </span><span>*/</span><span>public</span><span>$handled</span> = <span>false</span><span>;
    </span><span>/*</span><span>*
     * @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.
     </span><span>*/</span><span>public</span><span>$data</span><span>;

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


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

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

            </span><span>return</span><span>$removed</span><span>;
        }
    }

    </span><span>/*</span><span>*
     * 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.
     </span><span>*/</span><span>public</span><span>static</span><span>function</span> hasHandlers(<span>$class</span>, <span>$name</span><span>)
    {
        </span><span>if</span> (<span>empty</span>(self::<span>$_events</span>[<span>$name</span><span>])) {
            </span><span>//</span><span> 不存在,直接返回</span><span>return</span><span>false</span><span>;
        }
        </span><span>if</span> (<span>is_object</span>(<span>$class</span><span>)) {
            </span><span>//</span><span> 如果是一个 object,就获取其类名</span><span>$class</span> = <span>get_class</span>(<span>$class</span><span>);
        } </span><span>else</span><span> {
            </span><span>//</span><span> 如果是一个类名,就去掉 class 最左边的斜杠</span><span>$class</span> = <span>ltrim</span>(<span>$class</span>, '\\'<span>);
        }
        </span><span>//</span><span> 如果该类中找不到,就去父类中找,直到找到或者没有父类了为止</span><span>do</span><span> {
            </span><span>if</span> (!<span>empty</span>(self::<span>$_events</span>[<span>$name</span>][<span>$class</span><span>])) {
                </span><span>return</span><span>true</span><span>;
            }
        } </span><span>while</span> ((<span>$class</span> = <span>get_parent_class</span>(<span>$class</span>)) !== <span>false</span><span>);

        </span><span>return</span><span>false</span><span>;
    }

    </span><span>/*</span><span>*
     * 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.
     </span><span>*/</span><span>public</span><span>static</span><span>function</span> trigger(<span>$class</span>, <span>$name</span>, <span>$event</span> = <span>null</span><span>)
    {
        </span><span>if</span> (<span>empty</span>(self::<span>$_events</span>[<span>$name</span><span>])) {
            </span><span>return</span><span>;
        }
        </span><span>if</span> (<span>$event</span> === <span>null</span><span>) {
            </span><span>//</span><span> 事件不存在,就创建一个 Event 对象</span><span>$event</span> = <span>new</span><span>static</span><span>;
        }
        </span><span>//</span><span> 设置event对象的属性,默认是未被处理的</span><span>$event</span>->handled = <span>false</span><span>;
        </span><span>$event</span>->name = <span>$name</span><span>;

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

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

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

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

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

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

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

 

以上就介绍了Yii2的深入学习--yii\base\Event 类,包括了方面的内容,希望对PHP教程有兴趣的朋友有所帮助。

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Python中的class类和method方法的使用方法Python中的class类和method方法的使用方法Apr 21, 2023 pm 02:28 PM

类和方法的概念和实例类(Class):用来描述具有相同的属性和方法的对象的集合。它定义了该集合中每个对象所共有的属性和方法。对象是类的实例。方法:类中定义的函数。类的构造方法__init__():类有一个名为init()的特殊方法(构造方法),该方法在类实例化时会自动调用。实例变量:在类的声明中,属性是用变量来表示的,这种变量就称为实例变量,实例变量就是一个用self修饰的变量。实例化:创建一个类的实例,类的具体对象。继承:即一个派生类(derivedclass)继承基类(baseclass)的

使用jQuery替换元素的class名称使用jQuery替换元素的class名称Feb 24, 2024 pm 11:03 PM

jQuery是一种经典的JavaScript库,被广泛应用于网页开发中,它简化了在网页上处理事件、操作DOM元素和执行动画等操作。在使用jQuery时,经常会遇到需要替换元素的class名的情况,本文将介绍一些实用的方法,以及具体的代码示例。1.使用removeClass()和addClass()方法jQuery提供了removeClass()方法用于删除

python中class是什么意思python中class是什么意思May 21, 2019 pm 05:10 PM

class是python中的一个关键字,用来定义一个类,定义类的方法:class后面加一个空格然后加类名;类名规则:首字母大写,如果多个单词用驼峰命名法,如【class Dog()】。

PHP8.0中的事件处理库:EventPHP8.0中的事件处理库:EventMay 14, 2023 pm 05:40 PM

PHP8.0中的事件处理库:Event随着互联网的不断发展,PHP作为一门流行的后台编程语言,被广泛应用于各种Web应用程序的开发中。在这个过程中,事件驱动机制成为了非常重要的一环。PHP8.0中的事件处理库Event将为我们提供一个更加高效和灵活的事件处理方式。什么是事件处理在Web应用程序的开发中,事件处理是一个非常重要的概念。事件可以是任何一种用户行

SpringBoot怎么通过自定义classloader加密保护class文件SpringBoot怎么通过自定义classloader加密保护class文件May 11, 2023 pm 09:07 PM

背景最近针对公司框架进行关键业务代码进行加密处理,防止通过jd-gui等反编译工具能够轻松还原工程代码,相关混淆方案配置使用比较复杂且针对springboot项目问题较多,所以针对class文件加密再通过自定义的classloder进行解密加载,此方案并不是绝对安全,只是加大反编译的困难程度,防君子不防小人,整体加密保护流程图如下图所示maven插件加密使用自定义maven插件对编译后指定的class文件进行加密,加密后的class文件拷贝到指定路径,这里是保存到resource/corecla

PHP Class用法详解:让你的代码更清晰易读PHP Class用法详解:让你的代码更清晰易读Mar 10, 2024 pm 12:03 PM

在编写PHP代码时,使用类(Class)是一个非常常见的做法。通过使用类,我们可以将相关的功能和数据封装在一个单独的单元中,使代码更加清晰、易读和易维护。本文将详细介绍PHPClass的用法,并提供具体的代码示例,帮助读者更好地理解如何在实际项目中应用类来优化代码。1.创建和使用类在PHP中,可以使用关键字class来定义一个类,并在类中定义属性和方法。

Vue报错:无法正确使用v-bind绑定class和style,怎样解决?Vue报错:无法正确使用v-bind绑定class和style,怎样解决?Aug 26, 2023 pm 10:58 PM

Vue报错:无法正确使用v-bind绑定class和style,怎样解决?在Vue开发中,我们经常会用到v-bind指令来动态绑定class和style,但是有时候我们可能会遇到一些问题,如无法正确使用v-bind绑定class和style。在本篇文章中,我将为你解释这个问题的原因,并提供解决方案。首先,让我们先了解一下v-bind指令。v-bind用于将V

php提交表单通过后,弹出的对话框怎样在当前页弹出,该如何解决php提交表单通过后,弹出的对话框怎样在当前页弹出,该如何解决Jun 13, 2016 am 10:23 AM

php提交表单通过后,弹出的对话框怎样在当前页弹出php提交表单通过后,弹出的对话框怎样在当前页弹出而不是在空白页弹出?想实现这样的效果:而不是空白页弹出:------解决方案--------------------如果你的验证用PHP在后端,那么就用Ajax;仅供参考:HTML code<form name="myform"

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.