Table of Contents
Code implementation
Object level binding
Home Backend Development PHP Tutorial Detailed explanation of examples of EVENT events in Yii2

Detailed explanation of examples of EVENT events in Yii2

Aug 13, 2017 am 09:08 AM
event yii2 Example

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 &#39;猫:miao miao miao <br />&#39;;
        
        // 猫叫了之后 触发猫的 miao 事件
        $this->trigger(&#39;miao&#39;);
    }
}
Copy after login

Mouse.php

<?php

namespace frontend\event;

/**
 * 老鼠类
 * Class: \frontend\event\Mouse
 */
class Mouse
{
    public function run()
    {
        echo &#39;老鼠:有猫来了,赶紧跑啊~~<br />&#39;;
    }
}
Copy after login

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(&#39;miao&#39;, [$mouse, &#39;run&#39;]);

        // 猫发出叫声
        $cat->shout();
    }
}
Copy after login

Enter http://yourdomain.com/?r=event/test

in the browser to get

猫:miao miao miao 
老鼠:有猫来了,赶紧跑啊~~
Copy after login

Trigger the miao event by calling the cat's shout method, The mouse ran away

Suddenly, 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 &#39;狗:wang wang wang, 猫在哪里??&#39;;
    }
}
Copy after login

Modify frontend/controllers/EventController.php

Add dog looking for cat event

...
// 需事先给猫绑定 miao 事件才可以触发此事件
// 猫一叫,就触发老鼠的 run 方法
$cat->on(&#39;miao&#39;, [$mouse, &#39;run&#39;]);
$cat->on(&#39;miao&#39;, [$dog, &#39;findCat&#39;]); // 添加狗找猫事件

// 让猫发出叫声
$cat->shout();
...
Copy after login

Refresh http://yourdomain.com/?r=event/ in the browser test

get

猫:miao miao miao 
老鼠:有猫来了,赶紧跑啊~~
狗:wang wang wang, 猫在哪里??
Copy after login

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(&#39;miao&#39;, [$mouse, &#39;run&#39;]);
    $cat->on(&#39;miao&#39;, [$dog, &#39;findCat&#39;]);

    // 并非直接删除 $cat->on(&#39;miao&#39;, [$dog, &#39;findCat&#39;]);
    // 而是通过 off 解除绑定
    $cat->off(&#39;miao&#39;, [$dog, &#39;findCat&#39;]);

    // 让猫发出叫声
    $cat->shout();
}
...
Copy after login

So the final result is naturally less dog sound

Class level binding

But 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 事件
}
Copy after login

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() ,&#39;miao&#39;, [$mouse, &#39;run&#39;]);

    // 让猫发出叫声
    $cat->shout(); // 会触发 miao 事件
    (new Cat())->shout(); // 会触发 miao 事件
}
Copy after login

Refresh the page and get

猫:miao miao miao 
老鼠:有猫来了,赶紧跑啊~~
猫:miao miao miao 
老鼠:有猫来了,赶紧跑啊~~
Copy after login

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!

Statement of this Website
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

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

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1655
14
PHP Tutorial
1252
29
C# Tutorial
1226
24
SVM examples in Python SVM examples in Python Jun 11, 2023 pm 08:42 PM

Support Vector Machine (SVM) in Python is a powerful supervised learning algorithm that can be used to solve classification and regression problems. SVM performs well when dealing with high-dimensional data and non-linear problems, and is widely used in data mining, image classification, text classification, bioinformatics and other fields. In this article, we will introduce an example of using SVM for classification in Python. We will use the SVM model from the scikit-learn library

How to remove jquery in yii2 How to remove jquery in yii2 Feb 17, 2023 am 09:55 AM

How to remove jquery from yii2: 1. Edit the AppAsset.php file and comment out the "yii\web\YiiAsset" value in the variable $depends; 2. Edit the main.php file and add the configuration "'yii" under the field "components" \web\JqueryAsset' => ['js' => [],'sourcePath' => null,]," to remove the jquery script.

VUE3 Getting Started Example: Making a Simple Video Player VUE3 Getting Started Example: Making a Simple Video Player Jun 15, 2023 pm 09:42 PM

As the new generation of front-end frameworks continues to emerge, VUE3 is loved as a fast, flexible, and easy-to-use front-end framework. Next, let's learn the basics of VUE3 and make a simple video player. 1. Install VUE3 First, we need to install VUE3 locally. Open the command line tool and execute the following command: npminstallvue@next Then, create a new HTML file and introduce VUE3: &lt;!doctypehtml&gt;

Learn best practice examples of pointer conversion in Golang Learn best practice examples of pointer conversion in Golang Feb 24, 2024 pm 03:51 PM

Golang is a powerful and efficient programming language that can be used to develop various applications and services. In Golang, pointers are a very important concept, which can help us operate data more flexibly and efficiently. Pointer conversion refers to the process of pointer operations between different types. This article will use specific examples to learn the best practices of pointer conversion in Golang. 1. Basic concepts In Golang, each variable has an address, and the address is the location of the variable in memory.

Event processing library in PHP8.0: Event Event processing library in PHP8.0: Event May 14, 2023 pm 05:40 PM

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

PHP simple web crawler development example PHP simple web crawler development example Jun 13, 2023 pm 06:54 PM

With the rapid development of the Internet, data has become one of the most important resources in today's information age. As a technology that automatically obtains and processes network data, web crawlers are attracting more and more attention and application. This article will introduce how to use PHP to develop a simple web crawler and realize the function of automatically obtaining network data. 1. Overview of Web Crawler Web crawler is a technology that automatically obtains and processes network resources. Its main working process is to simulate browser behavior, automatically access specified URL addresses and extract all information.

VAE algorithm example in Python VAE algorithm example in Python Jun 11, 2023 pm 07:58 PM

VAE is a generative model, its full name is VariationalAutoencoder, which is translated into Chinese as variational autoencoder. It is an unsupervised learning algorithm that can be used to generate new data, such as images, audio, text, etc. Compared with ordinary autoencoders, VAEs are more flexible and powerful and can generate more complex and realistic data. Python is one of the most widely used programming languages ​​and one of the main tools for deep learning. In Python, there are many excellent machine learning and deep

Verification code usage examples in Gin framework Verification code usage examples in Gin framework Jun 23, 2023 am 08:10 AM

With the popularity of the Internet, verification codes have become a necessary process for login, registration, password retrieval and other operations. In the Gin framework, implementing the verification code function has become extremely simple. This article will introduce how to use a third-party library to implement the verification code function in the Gin framework, and provide sample code for readers' reference. 1. Install dependent libraries Before using the verification code, we need to install a third-party library goCaptcha. To install goCaptcha, you can use the goget command: $goget-ugithub

See all articles