The event mechanism is divided into two types: scanning type and binding type. The binding type is mainly used in Yii, and the binding type involves two methods: trigger() and on()
1. trigger() : The event is triggered by calling the yii\base\Component::trigger() method, which must pass the event name, you can also pass an event object to pass parameters to the event handler. (Recommended learning: yii tutorial)
2. on(): Sometimes you want all instances of a class to respond to a triggered event rather than a specified instance For events, instead of attaching event handlers to each instance one by one, the handler is attached at the class level by calling the static method yii\base\Event::on().
Let’s take a look at a specific example: (Create a cat and a mouse. When the cat meows, the mouse is triggered to run away)
The above is the code in the cat.php class. Since the screenshots are incomplete, I will add two more. Let’s take a look at mouse.php
How can we associate these two classes? Of course, we need to rely on the controller to call these two classes (because the cat class has already called the component class file, so there is no need to call it again when using run here)
Extension:
##
The above is the detailed content of How to bind events in yii. For more information, please follow other related articles on the PHP Chinese website!