Home  >  Article  >  PHP Framework  >  What is the event of yii

What is the event of yii

(*-*)浩
(*-*)浩Original
2019-11-14 16:42:352676browse

What is the event of yii

Events

Events allow custom code to be "injected" to a specific execution point in existing code. Attach custom code to an event and the code will be automatically executed when the event is triggered. (Recommended learning: yiitutorial)

For example, the messageSent event can be triggered when the mail program object successfully sends a message. If you want to track successfully sent messages, you can attach the corresponding tracking code to the messageSent event.

Yii introduces a base class named yii\base\Component to support events. If a class needs to trigger events, it should inherit yii\base\Component or its subclasses.

Event Handlers

The event handler is a PHP callback function that will be executed when the event it is attached to is triggered. You can use one of the following callback functions:

PHP global function specified in string form, such as 'trim';

Object method specified in array form of object name and method name, such as [$object, $method] ;

Static class method specified in the form of an array of class name and method name, such as [$class, $method];

Anonymous function, such as function ($event) { ... }.

The format of the event handler is:

function ($event) {
    // $event 是 yii\base\Event 或其子类的对象
}

Through the $event parameter, the event handler obtains the following information about the event:

event name: event name

event sender: the object that calls the trigger() method

custom data: the data passed in when attaching the event handler, the default is empty, after Detailed description in the article

Attaching Event Handlers

Call the yii\base\Component::on() method to attach the handler to the event. Such as:

$foo = new Foo;

// 处理器是全局函数
$foo->on(Foo::EVENT_HELLO, 'function_name');

// 处理器是对象方法
$foo->on(Foo::EVENT_HELLO, [$object, 'methodName']);

// 处理器是静态类方法
$foo->on(Foo::EVENT_HELLO, ['app\components\Bar', 'methodName']);

// 处理器是匿名函数
$foo->on(Foo::EVENT_HELLO, function ($event) {
    //事件处理逻辑
});

The above is the detailed content of What is the event of yii. For more information, please follow other related articles on the PHP Chinese website!

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
Previous article:what is yii frameworkNext article:what is yii framework