mirror of https://github.com/flightphp/core
You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
41 lines
1006 B
41 lines
1006 B
<?php
|
|
|
|
declare(strict_types=1);
|
|
|
|
namespace flight\core;
|
|
|
|
class EventDispatcher
|
|
{
|
|
/** @var array<string, array<int, callable>> */
|
|
protected array $listeners = [];
|
|
|
|
/**
|
|
* Register a callback for an event.
|
|
*
|
|
* @param string $event Event name
|
|
* @param callable $callback Callback function
|
|
*/
|
|
public function on(string $event, callable $callback): void
|
|
{
|
|
if (isset($this->listeners[$event]) === false) {
|
|
$this->listeners[$event] = [];
|
|
}
|
|
$this->listeners[$event][] = $callback;
|
|
}
|
|
|
|
/**
|
|
* Trigger an event with optional arguments.
|
|
*
|
|
* @param string $event Event name
|
|
* @param mixed ...$args Arguments to pass to the callbacks
|
|
*/
|
|
public function trigger(string $event, ...$args): void
|
|
{
|
|
if (isset($this->listeners[$event]) === true) {
|
|
foreach ($this->listeners[$event] as $callback) {
|
|
call_user_func_array($callback, $args);
|
|
}
|
|
}
|
|
}
|
|
}
|