Event introduction
Using events, you can trigger the execution of a preset piece of code at a specific point in time. Events are not only a way of code decoupling, but also a way of designing business processes. model. In modern software, events are everywhere. For example, if you post a Weibo, an event will be triggered, causing people who follow you to see your new content. For events, there are several elements:
What kind of event is this? In a software system, there are many events. Publishing a new Weibo is an event, and deleting a Weibo is also an event.
Who triggered the event? What you post on Weibo is the event you trigger.
Who is responsible for monitoring this event? Or who knows if this event happened? The module on the server that handles user registration will definitely not receive your new Weibo event.
How to handle the event? For the event of publishing a new Weibo, it is to notify other users who follow you.
What is the event-related data? For publishing a new Weibo event, the data contained must at least include the content of the new Weibo, time, etc.
Code implementation
Object level binding
Case introduction: There is a cat, and the mouse will run away when it calls.
In order to implement this example, we create the event folder in the frontend folder
In# There are 2 class files in ##event folder, one Cat class and one Mouse class
<?php namespace frontend\event; /** * 猫类 * Class: \frontend\event\Cat * * 为了让猫具有事件能力 * 所以要继承 \yii\base\Component * >>> \yii\base\Component 对 \yii\base\Event 的 on 方法进行重写 * >>> \yii\base\Event 适合类级绑定 * >>> \yii\base\Component 适合对象级绑定 */ class Cat extends \yii\base\Component { /** * 猫发出叫声 */ public function shout() { echo '猫:miao miao miao <br />'; // 猫叫了之后 触发猫的 miao 事件 $this->trigger('miao'); } }Mouse.php
<?php namespace frontend\event; /** * 老鼠类 * Class: \frontend\event\Mouse */ class Mouse { public function run() { echo '老鼠:有猫来了,赶紧跑啊~~<br />'; } }EventController.php
<?php namespace frontend\controllers; use frontend\event\Cat; use frontend\event\Mouse; /** * Class: \frontend\controllers\Event */ class EventController extends \yii\web\Controller { public function actionTest() { $cat = new Cat(); $mouse = new Mouse(); // 需事先给猫绑定 miao 事件才可以触发此事件 // 猫一叫,就触发老鼠的 run 方法 $cat->on('miao', [$mouse, 'run']); // 猫发出叫声 $cat->shout(); } }Enter http://yourdomain.com/?r=event/test
in the browser to get
猫:miao miao miao 老鼠:有猫来了,赶紧跑啊~~Trigger the miao event by calling the cat's shout method, The mouse ran awaySuddenly, one day, the dog joined this case. As long as the cat barks, the dog will go to the cat
so also add the dog member Dog in the event folder
.php
<?php namespace frontend\event; /** * Class \frontend\event\Dog */ class Dog extends \yii\base\Component { /** * 找猫 */ public function findCat() { echo '狗:wang wang wang, 猫在哪里??'; } }Modify frontend/controllers/EventController.php
Add dog looking for cat event
... // 需事先给猫绑定 miao 事件才可以触发此事件 // 猫一叫,就触发老鼠的 run 方法 $cat->on('miao', [$mouse, 'run']); $cat->on('miao', [$dog, 'findCat']); // 添加狗找猫事件 // 让猫发出叫声 $cat->shout(); ...Refresh http://yourdomain.com/?r=event/ in the browser test
get
猫:miao miao miao 老鼠:有猫来了,赶紧跑啊~~ 狗:wang wang wang, 猫在哪里??Suddenly, the dog feels bored and doesn’t want to look for the cat anymore. It just barks.
Then we only need to unbind the dog looking for the cat event
Modify frontend /controllers/EventController.php
use frontend\event\Cat; use frontend\event\Mouse; use frontend\event\Dog; ... public function actionTest() { $cat = new Cat(); $mouse = new Mouse(); $dog = new Dog(); // 需事先给猫绑定 miao 事件才可以触发此事件 // 猫一叫,就触发老鼠的 run 方法 $cat->on('miao', [$mouse, 'run']); $cat->on('miao', [$dog, 'findCat']); // 并非直接删除 $cat->on('miao', [$dog, 'findCat']); // 而是通过 off 解除绑定 $cat->off('miao', [$dog, 'findCat']); // 让猫发出叫声 $cat->shout(); } ...So the final result is naturally less dog soundClass level bindingBut there is a problem, the above events are directly targeted
$cat The assigned object, is to add
(new Cat())->shout(); at the end of the actionTest method in frontend/controllers/EventController.php The miao event will not be triggered
public function actionTest() { ... // 让猫发出叫声 $cat->shout(); // 会触发 miao 事件 (new Cat())->shout(); // 不会触发 miao 事件 }Reason:
Event binding is done through the $cat objectIs there a way that the mouse will run away as long as the sound is made by the cat? Woolen cloth? ?
This requires the use of
class-level event binding
The class-level event binding requires the use of the \yii\base\Event class Modify frontend/controllers/EventController.php
use frontend\event\Cat; use frontend\event\Mouse; use yii\base\Event; ... public function actionTest() { $cat = new Cat(); $mouse = new Mouse(); // 类级别的事件绑定 // 只要猫发出声音,不管是什么猫,都会触发老鼠的 run 方法 Event::on(Cat::className() ,'miao', [$mouse, 'run']); // 让猫发出叫声 $cat->shout(); // 会触发 miao 事件 (new Cat())->shout(); // 会触发 miao 事件 }Refresh the page and get
猫:miao miao miao 老鼠:有猫来了,赶紧跑啊~~ 猫:miao miao miao 老鼠:有猫来了,赶紧跑啊~~Summary
- ##Event binding classification object level and class level binding Defined
- The object level is only effective for a certain instantiated object
- The class level is effective for all instantiated objects
- If there are any errors in the above understanding, please feel free to raise them and correct them
The above is the detailed content of Detailed explanation of examples of EVENT events in Yii2. For more information, please follow other related articles on the PHP Chinese website!

DependencyinjectioninPHPisadesignpatternthatenhancesflexibility,testability,andmaintainabilitybyprovidingexternaldependenciestoclasses.Itallowsforloosecoupling,easiertestingthroughmocking,andmodulardesign,butrequirescarefulstructuringtoavoidover-inje

PHP performance optimization can be achieved through the following steps: 1) use require_once or include_once on the top of the script to reduce the number of file loads; 2) use preprocessing statements and batch processing to reduce the number of database queries; 3) configure OPcache for opcode cache; 4) enable and configure PHP-FPM optimization process management; 5) use CDN to distribute static resources; 6) use Xdebug or Blackfire for code performance analysis; 7) select efficient data structures such as arrays; 8) write modular code for optimization execution.

OpcodecachingsignificantlyimprovesPHPperformancebycachingcompiledcode,reducingserverloadandresponsetimes.1)ItstorescompiledPHPcodeinmemory,bypassingparsingandcompiling.2)UseOPcachebysettingparametersinphp.ini,likememoryconsumptionandscriptlimits.3)Ad

Dependency injection provides object dependencies through external injection in PHP, improving the maintainability and flexibility of the code. Its implementation methods include: 1. Constructor injection, 2. Set value injection, 3. Interface injection. Using dependency injection can decouple, improve testability and flexibility, but attention should be paid to the possibility of increasing complexity and performance overhead.

Implementing dependency injection (DI) in PHP can be done by manual injection or using DI containers. 1) Manual injection passes dependencies through constructors, such as the UserService class injecting Logger. 2) Use DI containers to automatically manage dependencies, such as the Container class to manage Logger and UserService. Implementing DI can improve code flexibility and testability, but you need to pay attention to traps such as overinjection and service locator anti-mode.

Thedifferencebetweenunset()andsession_destroy()isthatunset()clearsspecificsessionvariableswhilekeepingthesessionactive,whereassession_destroy()terminatestheentiresession.1)Useunset()toremovespecificsessionvariableswithoutaffectingthesession'soveralls

Stickysessionsensureuserrequestsareroutedtothesameserverforsessiondataconsistency.1)SessionIdentificationassignsuserstoserversusingcookiesorURLmodifications.2)ConsistentRoutingdirectssubsequentrequeststothesameserver.3)LoadBalancingdistributesnewuser

PHPoffersvarioussessionsavehandlers:1)Files:Default,simplebutmaybottleneckonhigh-trafficsites.2)Memcached:High-performance,idealforspeed-criticalapplications.3)Redis:SimilartoMemcached,withaddedpersistence.4)Databases:Offerscontrol,usefulforintegrati


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

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

WebStorm Mac version
Useful JavaScript development tools

SublimeText3 English version
Recommended: Win version, supports code prompts!

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

Atom editor mac version download
The most popular open source editor
