shieldon / event-dispatcher

PHP的事件分发器。

1.0.0 2020-08-14 02:15 UTC

This package is auto-updated.

Last update: 2024-09-14 12:02:16 UTC


README

Build Status codecov License: MIT

该包作为Shieldon Firewall 2的一部分被设计。您也可以在您的项目中使用它。

安装

使用PHP Composer

composer require shieldon/event-dispatcher

或者,下载它并包含Shieldon自动加载器。

require 'autoload.php';

使用方法

添加监听器

/**
 * @param string        $name      The name of an event.
 * @param string|array  $func      Callable function or class.
 * @param int           $priority  The execution priority.
 * 
 * @return bool
 */
\Shieldon\Event\Event::addLister(string $name, $func, int $priority = 10): bool

请注意,优先级必须是唯一的。当添加监听器时,该方法返回true;当优先级已被其他监听器占用时返回false。

分发

/**
 * @param string $name The name of an event.
 * @param array  $args The arguments.
 * 
 * @return mixed
 */
\Shieldon\Event\Event::doDispatch(string $name, array $args = []): mixed

返回过滤后的结果,类似于WordPress的过滤器。如果您不需要返回值,可以忽略它。

示例

闭包

添加监听器。

\Shieldon\Event\Event::addListener('test_1', function() {
    echo 'This is a closure function call.';
});

分发。

$result = \Shieldon\Event\Event::doDispatch('test_1');

函数

监听器的函数。

function test_event_disptcher()
{
    echo 'This is a function call.';
}

添加监听器。

\Shieldon\Event\Event::addListener('test_2', 'test_event_disptcher');

分发。

$result = \Shieldon\Event\Event::doDispatch('test_2');

添加监听器。

$example = new Example();

\Shieldon\Event\Event::addListener('test_3', [$example, 'example1']);

分发。

$result = \Shieldon\Event\Event::doDispatch('test_3');

希望这能帮到您。

作者

许可证

MIT