The EventManager class provides a lightweight event system that allows you to register, detach, and trigger named events dynamically at runtime.
It is designed to simplify the management of callbacks (closures) that respond to specific application events.
This implementation supports:
Attaching and Triggering Events
<?php
use Krystal\Event\EventManager;
$events = new EventManager();
// Attach an event called 'onSave'
$events->attach('onSave', function() {
echo 'Data has been saved!';
});
// Trigger the event manually
$events->trigger('onSave'); // Output: Data has been saved!
You can trigger events simply by calling them as methods:
$events->onSave(); // Equivalent to $events->trigger('onSave');
You can attach multiple events at once using an associative array:
$events->attachMany([
'onStart' => function() { echo 'Application started'; },
'onStop' => function() { echo 'Application stopped'; }
]);
$events->trigger('onStart'); // Output: Application started
$events->trigger('onStop'); // Output: Application stopped
// Remove one event
$events->detach('onSave');
// Remove all registered events
$events->detachAll();
If you try to detach an event that doesnβt exist, a RuntimeException will be thrown.
$events->has('onStart'); // true or false
$events->hasMany(['onStart', 'onStop']); // true if all exist
echo $events->countAll(); // e.g., 2
InvalidArgumentException β thrown if event name is not a string or listener is not callable.
RuntimeException β thrown when trying to trigger or detach a non-existing event.