dhenfie/event-dispatcher

简单的PHP事件调度器

1.0.0 2023-09-25 15:25 UTC

This package is auto-updated.

Last update: 2024-09-29 06:08:48 UTC


README

这是一个简单的PHP事件调度器。它允许应用组件通过事件相互通信,而无需了解彼此的任何信息。

安装

composer require dhenfie/event-dispatcher

用法

# 注册监听器

监听器是一种监听事件并在事件发生时执行某些操作的东西。要注册监听器,请使用 EventDispatcher::listen($eventName, $listener) 方法。

监听器是一个实现了 EventListenerInterface 接口的类。

以下是一个作为事件监听器的示例类

<?php
// file SendToEmail.php
use Dhenfie\EventDispatcher\EventDispatcher;

class SendToEmail implements EventListenerInterface {
 
    public function handle(array $params = []) {
        // send an email to the user
        Mail::send($params['email'], $params['message']);
    }
}

接下来,使用 `listen()` 方法注册监听器类

<?php
use Dhenfie\EventDispatcher\EventDispatcher;
use SendToEmail;

// daftarkan pendengar menggunakan static method `listen`
EventDispatcher::listen('passwordRequestSend', new SendToEmail());

passwordRequestSend 事件发生时,SendToMail 对象上的 handle() 方法 将被执行。

触发事件

使用 dispatch() 方法触发特定事件的发生。

示例

<?php
use Dhenfie\EventDispatcher\EventDispatcher;

// trigger event passwordRequestSend
EventDispatcher::dispatch('passwordRequestSend');

dispatch 方法还接受第二个参数,这是一个可以用来向监听器发送额外信息的数组。

示例

<?php

use Dhenfie\EventDispatcher\EventDispatcher;

EventDispatcher::dispatch('passwordRequestSend', ['email' => 'example@mail.com', 'message' => 'Your password reset token we send your email']);