cleup/events

一个方便的事件系统,用于修改和扩展Web应用平台

v1.0.1 2024-06-17 06:59 UTC

This package is auto-updated.

Last update: 2024-09-17 07:27:57 UTC


README

安装

使用composer安装cleup/events

composer require cleup/events

用法

事件初始化
use Cleup\Components\Events\Event;

# Simple event
Event::apply('customEvent');

# Event with arguments
$name = 'Eduard';
$age = 30;
$fields = array(
    'login' => 'priveted',
    'type' => 'admin'
);
Event::apply('customEvent', $name, $age, $fields, ...);
添加新事件
use Cleup\Components\Events\Event;

# With the function
Event::add('customEvent', function () {
   print_r("Hi, I've been added to the event thread");
});

# Using the function name
function helloWorld () {
    print_r('Hello World!');
}

Event::add('customEvent', 'helloWorld');

# Using the class method
Event::add('customEvent', [Example::class, 'get']);
添加事件的修饰符

分配回调执行的顺序。

use Cleup\Components\Events\Event;

Event::add('getPosts', function (&$postList) {
    // ...
})->position(100);

为事件创建一个ID。您可以使用此ID删除特定事件

use Cleup\Components\Events\Event;

Event::add('getPosts', function (&$postList) {
    // ...
})->id('isBadPost');

执行一次。如果事件多次执行或循环执行,则修饰符可能很有用。

use Cleup\Components\Events\Event;

Event::add('postItem', function ($post) {
    // This event will be deleted immediately after execution
})->once();

$posts = array(
    0 => [
        'id' => 1
        'title' => 'First post'
    ],
    1 => [
        'id' => 2
        'title' => 'Hello world!'
    ]
)

foreach($posts as $post) {
    // The event will be executed only once and will be deleted
    Event::apply('postItem', $post);
}
删除事件
Event::delete('getdPosts');

// Delete event by ID
Event::delete('getdPosts', 'isBadPost');