Event


How to define events?

All operations of the event system are statically called through the think\facade\Event class

The event system uses the observer pattern (please refer to PHP design pattern) to provide a better way to decouple applications.

Where you need to listen for events, for example, below we add the following event triggering code after the user completes the login operation:

// 触发UserLogin事件 用于执行用户登录后的一系列操作
Event::trigger('UserLogin');


Here UserLogin represents an event Identification, if you define a separate event class, you can use the event class name (you can even pass in an event class instance).

// 直接使用事件类触发
event('app\event\UserLogin');

Event classes can be quickly generated through the command line

php think make:event UserLogin

An app\event\UserLogin event class will be generated by default, or you can specify the complete class name to generate.

We can add methods to event classes

namespace app\event;

use app\model\User;

class UserLogin
{
    public $user;

    public function __construct(User $user)
    {
        $this->user = $user;
    }
}

General event classes do not need to inherit any other classes.

You can bind an event identifier to the event class. It is generally recommended to bind in batches directly in the event.php event definition file of the application.

return [
    'bind'    =>    [
        'UserLogin' => 'app\event\UserLogin',
        // 更多事件绑定
    ],
];

If you need dynamic binding, you can use

Event::bind(['UserLogin' => 'app\event\UserLogin']);

ThinkPHP's event system does not rely on event classes. If there are no additional requirements, it can be used only through event identification, eliminating the need to define events. class trouble.

If you do not define an event class, there is no need to bind. For most scenarios, there may indeed be no need to define an event class.

You can pass in an event parameter in the event method

// user是当前登录用户对象实例
event('UserLogin', $user);

Listen for events

You can manually register an event listener

Event::listen('UserLogin', function($user) {
    // 
});

Or use a listening class to perform monitoring

Event::listen('UserLogin', 'app\listener\UserLogin');

You can quickly generate an event listening class through the command line

php think make:listener UserLogin

By default, an app\listener\UserLogin event listening class will be generated, also Full class name generation can be specified.

The event listening class only needs to define a handle method and supports dependency injection.

<?php
namespace app\listener;

class UserLogin
{
    public function handle($user)
    {
        // 事件监听处理
    }   
}

If false is returned in the handle method, it means that the monitoring is terminated, and the monitoring after the event will no longer be executed.

It is generally recommended to define the monitoring of the corresponding event directly in the event definition file.

return [
    'bind'    =>    [
        'UserLogin' => 'app\event\UserLogin',
        // 更多事件绑定
    ],
    'listen'  =>    [
        'UserLogin'    =>    ['app\listener\UserLogin'],
        // 更多事件监听
    ],
];

Event subscription

You can listen to multiple events in one listener through the event subscription mechanism, for example, generate an event subscriber class through the command line ,

php think make:subscribe User

The app\subscribe\User class will be generated by default, or you can specify the complete class name to generate.

Then you can add listening methods for different events in the event subscription class, for example.

<?php
namespace app\subscribe;

class User
{
    public function onUserLogin($user)
    {
        // UserLogin事件响应处理
    }

    public function onUserLogout($user)
    {
        // UserLogout事件响应处理
    }
}

The naming convention for methods to listen to events is on event identifier (camel case naming), and then register event subscribers in the event definition file.

return [
    'bind'    =>    [
        'UserLogin' => 'app\event\UserLogin',
        // 更多事件绑定
    ],
    'listen'  =>    [
        'UserLogin'    =>    ['app\listener\UserLogin'],
        // 更多事件监听
    ],
    'subscribe'    =>    [
       'app\subscribe\User',
        // 更多事件订阅
    ],
];

If you want to add event prefix identifiers uniformly, you can define the eventPrefix attribute.

<?php
namespace app\subscribe;

class User
{
    protected $eventPrefix = 'User';

    public function onLogin($user)
    {
        // UserLogin事件响应处理
    }

    public function onLogout($user)
    {
        // UserLogout事件响应处理
    }
}

If you want to customize the subscription method (or method specification), you can define the subscribe method implementation.

<?php
namespace app\subscribe;

use think\Event;

class User
{
    public function onUserLogin($user)
    {
        // UserLogin事件响应处理
    }

    public function onUserLogout($user)
    {
        // UserLogout事件响应处理
    }

    public function subscribe(Event $event)
    {
        $event->listen('UserLogin', [$this,'onUserLogin']);
        $event->listen('UserLogout',[$this,'onUserLogout']);
    }
}

If you need to register dynamically, you can use

Event::subscribe('app\index\subscribe\User');

Built-in events

Built-in system events include:


##HttpRunApplication start tag bitNoneHttpEndApplication end tag bitCurrent response object instanceLogWriteLog write method tag bit Currently written log informationLogLevelLog writing label bitAn array containing log type and log information RouteLoadedRoute loading completedNone
EventDescriptionParameters
AppInitApplication initialization tag bitNone
AppInit event definition must be global Defined in the event definition file, other events can be defined in the application's event definition file.

Some of the original behavior tags in 5.1 have been abandoned, and all canceled tags can be replaced by better middleware. Middleware can be thought of as special events related to processing requests and responding to output. In fact, the handler method of middleware only has special parameters and return values.


The callback of database operation is also called query event. It is a callback method designed for CURD operation of database. It mainly includes:


##Eventbefore_selectselectbefore_findfindafter_insertinsertafter_updateupdateafter_deletedelete##The parameter of the query event is the current query object instance.
Description
Before query Callback
Pre-query callback
Callback after successful operation
Callback after successful operation
Callback after successful operation
Model events include:


##Hook Corresponding operationafter_readAfter querybefore new additionAfter new addition Before update##after_updateAfter updatebefore_write Before writingafter_writeAfter writing before_deletebefore deletionafter_deleteafter deletion
before_insert
after_insert
before_update