Home > PHP Framework > ThinkPHP > ThinkPHP6.0: event system and the use of query events and model events

ThinkPHP6.0: event system and the use of query events and model events

爱喝马黛茶的安东尼
Release: 2019-12-16 14:19:15
forward
5613 people have browsed it

ThinkPHP6.0: event system and the use of query events and model events

In the latest version 6.0, a new event system was introduced to replace the behavior of version 5.1, and also took over database events and model events.

This article mainly describes the new version of the event system and the use of query events and model events.

Define events

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

Event system The observer pattern is used to provide a better way to decouple applications. Where you need to listen for events, add the following code:

Event::trigger('UserLogin');
Copy after login

Or use the helper function

event('UserLogin');
Copy after login

Here UserLogin represents an event identifier. 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');
Copy after login

Event classes can be quickly generated through the command line

php think make:event UserLogin
Copy after login

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;
    }
}
Copy after login

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

You can bind an event identifier to the event class

Event::bind('UserLogin', 'app\event\UserLogin');
Copy after login

or bind it in batches in the application's event.php event definition file.

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

If you do not define an event class, there is no need to bind.

ThinkPHP's event system does not rely on event classes. If there are no additional requirements, it can be used only through event identification.

You can pass in an event parameter in the event method

event('UserLogin', $user);
Copy after login

Event monitoring

You can manually register an event monitoring

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

Or use the listening class

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

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

php think make:listener UserLogin
Copy after login

By default, an app\listener\UserLogin event listening class will be generated, or you can specify the complete class name to generate .

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

<?php
namespace app\listener;
class UserLogin
{
    public function handle($user)
    {
        // 事件监听处理
    }   
}
Copy after login

If false is returned in the handler 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 [
    &#39;bind&#39;    =>    [
        &#39;UserLogin&#39; => &#39;app\event\UserLogin&#39;,
        // 更多事件绑定
    ],
    &#39;listen&#39;  =>    [
        &#39;UserLogin&#39;    =>    [&#39;\app\listener\UserLogin&#39;],
        // 更多事件监听
    ],
];
Copy after login

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
Copy after login

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)
    {
        // 事件响应处理
    }
    public function onUserLogout($user)
    {
        // 事件响应处理
    }
}
Copy after login

The naming convention for listening event methods is on event identification (camel case naming), and then register the event subscription

Event::subscribe(&#39;app\subscribe\User&#39;);
Copy after login

It is generally recommended to define it directly in the event definition file

return [
    &#39;bind&#39;    =>    [
        &#39;UserLogin&#39; => &#39;app\event\UserLogin&#39;,
        // 更多事件绑定
    ],
    &#39;listen&#39;  =>    [
        &#39;UserLogin&#39;    =>    [&#39;\app\listener\UserLogin&#39;],
        // 更多事件监听
    ],
    &#39;subscribe&#39;    =>    [
       &#39;\app\subscribe\User&#39;,
        // 更多事件订阅
    ],
];
Copy after login

Built-in events

Built-in system events include:

ThinkPHP6.0: event system and the use of query events and model events

AppInit event definition must be defined in the global event definition file, and 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 better replaced by middleware. Middleware can be thought of as special events related to processing requests and responding to output. In fact, the handle method of middleware only has special parameters and return values.

Query event

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

ThinkPHP6.0: event system and the use of query events and model events

Use the following method to register database query events

\think\facade\Db::event(&#39;before_select&#39;, function ($query) {
    // 事件处理
    return $result;
});
Copy after login

The same query event can register multiple response executions. Query events have also been taken over by the event system in the new version, so if you register a before_select query event listener, the bottom layer actually registers a listener for the event identified as db.before_select.

The query event method parameter has only one parameter: the current query object. But you can add additional parameters through dependency injection.

Model events

Model events refer to operational behaviors triggered when querying and writing the model.

Model events only take effect when calling the model method, and the query constructor operation is invalid.

The model supports the following events:

ThinkPHP6.0: event system and the use of query events and model events

#The registered callback method supports passing in one parameter (current model object instance), but supports dependency injection way to add additional parameters.

If the before_write, before_insert, before_update, before_delete event method returns false or throws think\exception\

ModelEventException异常的话,则不会继续执行后续的操作。

模型事件定义

最简单的方式是在模型类里面定义静态方法来定义模型的相关事件响应。

<?php
namespace app\index\model;
use think\Model;
use app\index\model\Profile;
class User extends Model
{
    public static function onBeforeUpdate($user)
    {
    if (&#39;thinkphp&#39; == $user->name) {
        return false;
        }
    }
    
    public static function onAfterDelete($user)
    {
Profile::destroy($user->id);
    }
}
Copy after login

参数是当前的模型对象实例,支持使用依赖注入传入更多的参数。

模型事件观察者

如果希望模型的事件单独管理,可以给模型注册一个事件观察者,例如:

<?php
namespace app\index\model;
use think\Model;
class User extends Model
{
    protected $observerClass = &#39;app\index\observer\User&#39;;
}
Copy after login

User观察者类定义如下:

<?php
namespace app\index\observer;
use app\index\model\Profile;
class User
{
    public function onBeforeUpdate($user)
    {
    if (&#39;thinkphp&#39; == $user->name) {
        return false;
        }
    }
    
    public function onAfterDelete($user)
    {
Profile::destroy($user->id);
    }
}
Copy after login

观察者类的事件响应方法的第一个参数就是模型对象实例,你依然可以通过依赖注入传入其它的对象参数。

PHP中文网,大量的免费ThinkPHP入门教程,欢迎在线学习!

本文转自:https://blog.thinkphp.cn/1037387

The above is the detailed content of ThinkPHP6.0: event system and the use of query events and model events. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:thinkphp.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template