search
HomePHP FrameworkThinkPHPThinkPHP6 event and hook usage guide: implementing triggering and monitoring

ThinkPHP6 event and hook usage guide: implementing triggering and monitoring

ThinkPHP6 Events and Hooks Usage Guide: Implementing Triggering and Monitoring

Overview
During the development process, we often need to handle some events, such as when the user registration is successful. Send an email reminder later, or update the cache after the product is removed from the shelves, etc. In order to better manage these events, ThinkPHP6 provides event and hook mechanisms, making event triggering and monitoring more flexible and convenient.

1. Events and listeners
Events refer to things that happen during program execution, such as successful user registration, successful order placement, etc. Listeners respond to events, that is, perform specific operations after an event occurs. Events and listeners in ThinkPHP6 are managed using the observer mode, which decouples the triggering of events and the corresponding operations.

  1. Register event listener
    In ThinkPHP6, you can register an event listener by defining a listener class. The listener class is located in the app/listener directory. When defining, you need to inherit the thinklistenerListener class and implement its handle() method. For example, we define a UserRegisteredListener class to listen for user registration success events:
namespace applistener;

use thinklistenerListener;

class UserRegisteredListener extends Listener
{
    // 定义事件监听方法
    public function handle($event)
    {
        // 处理事件的操作
        // 比如发送邮件通知
        // ...
    }
}

In the handle() method, you can write the operations that need to be performed after the corresponding event occurs.

  1. The corresponding relationship between registered events and listeners
    In ThinkPHP6, you can specify the corresponding relationship between events and listeners in the event definition file. The event definition file is located in the app/event.php file, and the corresponding relationship between events and listeners is defined through a configuration array.
return [
    'bind' => [
        'UserRegistered' => [
            'applistenerUserRegisteredListener',
        ],
    ],
];

The above configuration indicates that when the event UserRegistered occurs, the handle() method of UserRegisteredListener will be triggered.

2. Triggering events
When an event occurs, we can notify the system by triggering the event, thereby executing the corresponding listener.

  1. Methods for event triggering
    ThinkPHP6 provides two ways to trigger events:

(1) Direct triggering: directly through the dispatch() method of the system class to trigger the event.

use thinkacadeEvent;

// 触发 UserRegistered 事件,可以传递参数
Event::dispatch('UserRegistered', $userData);

(2) Triggering within the container: Trigger the event through the event() method of the container. If it is called in the constructor, automatic dependency injection can be used.

use thinkacadeevent;

// 通过容器内触发 UserRegistered 事件,可以传递参数
app('event')->trigger('UserRegistered', $userData);
  1. Create event object
    In the event listener processing method, we can receive the parameters passed when the event is triggered by defining the event object. Creating an event object encapsulates parameters for easy use in listeners.
namespace applistener;

use thinklistenerListener;
use appeventUserRegisteredEvent; // 引入事件类

class UserRegisteredListener extends Listener
{
    public function handle($event)
    {
        // 将传递的参数封装为事件对象
        $userRegisteredEvent = new UserRegisteredEvent($event);
        
        // 使用事件对象的属性
        $username = $userRegisteredEvent->username;
        // ...
    }
}

3. Hooks
Hooks are some key nodes reserved in the system. By registering operations on the hook nodes, the corresponding extended functions can be achieved. Hook nodes are usually located in the core parts of the system, such as request start, request end, route resolution, etc. The hook mechanism in ThinkPHP6 is implemented through Middleware, which allows for more flexible control of the process.

  1. Register hook
    In ThinkPHP6, hooks can be registered through middleware. Middleware inherits from the thinkMiddleware class. You can customize middleware and implement corresponding operations in the middleware.
namespace appmiddleware;

use thinkacadeEvent;

class MyMiddleware
{
    public function handle($request, Closure $next)
    {
        // 钩子操作
        // ...

        return $next($request);
    }
}

In the above handle() method, you can write the operations that the corresponding hook node needs to perform. After the middleware is registered, it can be configured into the system's global middleware or routing middleware.

  1. Register global hooks
    Global hooks refer to hooks that will be triggered during the entire system request life cycle. In ThinkPHP6, global hooks can be registered through the middleware configuration item in the config/app.php file.
'middleware' => [
    // 注册全局钩子
    ppmiddlewareMyMiddleware::class,
    // ...
]
  1. Register routing hook
    Routing hook refers to a hook that will be triggered only when a specific route matches. In ThinkPHP6, routing hooks can be registered by specifying middleware in the route.
Route::rule('index', 'index/index')->middleware(ppmiddlewareMyMiddleware::class);

4. Summary
Through the event and hook mechanism, we can handle events that occur in the program more flexibly and perform corresponding operations after the event occurs. In ThinkPHP6, we can listen for events by registering listeners and perform specific operations when events occur. At the same time, we can also register middleware to implement corresponding hooks to achieve more refined process control.

In this way, we can decouple and separate various parts of the system and improve the scalability and maintainability of the system.

The above is the relevant content of the ThinkPHP6 event and hook usage guide. I hope it will be helpful for you to understand and apply the event and hook mechanism in ThinkPHP6.

The above is the detailed content of ThinkPHP6 event and hook usage guide: implementing triggering and monitoring. 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

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft