dida/eventbus

A lightweight PHP Event Bus library.

v1.1.2 2024-05-15 03:33 UTC

This package is auto-updated.

Last update: 2024-11-15 04:55:33 UTC


README

A lightweight PHP Event Bus library for Dida Framework.

API

public static $free_hook_mode = true;

public static $context        = null;
public static $global_context = null;

public static function hasEvent(string $event): bool;
public static function regEvent(string $event): void;
public static function unregEvent(string $event): void;

public static function addEvent(string $event): void;     // alias of regEvent.
public static function removeEvent(string $event): void;  // alias of unregEvent.

public static function hook(string $event, callable $callback, array $parameters = [], ?string $callback_id = null);
public static function unhook(string $event, ?string $callback_id = null): void;

public static function trigger(string $event, $context = false): void;

Code


use Dida\EventBus;

// Register an event.
EventBus::regEvent("YOUR.EVENT");

// Hook some callbacks.
...
EventBus::hook("YOUR.EVENT", your_callback_1, [param1, param2, ...]);
...
EventBus::hook("YOUR.EVENT", your_callback_2, [param1, param2, ...]);
...
EventBus::hook("YOUR.EVENT", your_callback_3, [param1, param2, ...]);

// Optional: Put some data to $context or $global_context if needed.

// Trigger an event and execute all hooked callbacks.
EventBus::trigger("YOUR.EVENT");

// or if you want to pass some context data for the callbacks of this event.
EventBus::trigger("YOUR.EVENT", $some_context_data);

// or if you want to pass some context data in another way.
EventBus::$context = some_context_data;
EventBus::$global_context = some_global_data;
EventBus::trigger("YOUR.EVENT");