In-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>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教程有兴趣的朋友有所帮助。

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



Concepts and instances of classes and methods Class (Class): used to describe a collection of objects with the same properties and methods. It defines the properties and methods common to every object in the collection. Objects are instances of classes. Method: Function defined in the class. Class construction method __init__(): The class has a special method (construction method) named init(), which is automatically called when the class is instantiated. Instance variables: In the declaration of a class, attributes are represented by variables. Such variables are called instance variables. An instance variable is a variable modified with self. Instantiation: Create an instance of a class, a specific object of the class. Inheritance: that is, a derived class (derivedclass) inherits the base class (baseclass)

Editor of Machine Power Report: Wu Xin The domestic version of the humanoid robot + large model team completed the operation task of complex flexible materials such as folding clothes for the first time. With the unveiling of Figure01, which integrates OpenAI's multi-modal large model, the related progress of domestic peers has been attracting attention. Just yesterday, UBTECH, China's "number one humanoid robot stock", released the first demo of the humanoid robot WalkerS that is deeply integrated with Baidu Wenxin's large model, showing some interesting new features. Now, WalkerS, blessed by Baidu Wenxin’s large model capabilities, looks like this. Like Figure01, WalkerS does not move around, but stands behind a desk to complete a series of tasks. It can follow human commands and fold clothes

Class is a keyword in Python, used to define a class. The method of defining a class: add a space after class and then add the class name; class name rules: capitalize the first letter. If there are multiple words, use camel case naming, such as [class Dog()].

jQuery is a classic JavaScript library that is widely used in web development. It simplifies operations such as handling events, manipulating DOM elements, and performing animations on web pages. When using jQuery, you often encounter situations where you need to replace the class name of an element. This article will introduce some practical methods and specific code examples. 1. Use the removeClass() and addClass() methods jQuery provides the removeClass() method for deletion

Event processing library in PHP8.0: Event With the continuous development of the Internet, PHP, as a popular back-end programming language, is widely used in the development of various Web applications. In this process, the event-driven mechanism has become a very important part. The event processing library Event in PHP8.0 will provide us with a more efficient and flexible event processing method. What is event handling? Event handling is a very important concept in the development of web applications. Events can be any kind of user row

When writing PHP code, using classes is a very common practice. By using classes, we can encapsulate related functions and data in a single unit, making the code clearer, easier to read, and easier to maintain. This article will introduce the usage of PHPClass in detail and provide specific code examples to help readers better understand how to apply classes to optimize code in actual projects. 1. Create and use classes In PHP, you can use the keyword class to define a class and define properties and methods in the class.

Vue error: Unable to use v-bind to bind class and style correctly, how to solve it? In Vue development, we often use the v-bind instruction to dynamically bind class and style, but sometimes we may encounter some problems, such as being unable to correctly use v-bind to bind class and style. In this article, I will explain the cause of this problem and provide you with a solution. First, let’s understand the v-bind directive. v-bind is used to bind V

Background Recently, key business codes have been encrypted for the company framework to prevent the engineering code from being easily restored through decompilation tools such as jd-gui. The configuration and use of the related obfuscation scheme are relatively complex and there are many problems for the springboot project, so the class files are encrypted and then passed The custom classloder is decrypted and loaded. This solution is not absolutely safe. It only increases the difficulty of decompilation. It prevents gentlemen but not villains. The overall encryption protection flow chart is shown in the figure below. Maven plug-in encryption uses custom maven plug-in to compile. The class file specified is encrypted, and the encrypted class file is copied to the specified path. Here, it is saved to resource/corecla.
