folleah/psr7-event-emitter

PSR-7 event-emitter implementation

dev-master 2017-06-13 10:06 UTC

This package is not auto-updated.

Last update: 2024-09-23 17:16:48 UTC


README

More about functions

Some examples:

  • Security framework that will prevent saving/accessing data when a user doesn't have permission.
  • A Common full page caching system
  • Logging package to track all actions taken within the application

Example:

use Event\Event;
use Event\EventManager;

$onGreeted = function($var) {
    echo "Hi, {$var}.</br>";
};

$onAsked = function() {
    echo "How are you?</br>";
};

$onGoodbye = function() {
    echo "Bye!</br>";
};

$eventManager = new EventManager;
$event = new Event('acquaintance');

// Listen this event with priority
$eventManager->attach('acquaintance', $onGreeted, 2);
$eventManager->attach('acquaintance', $onAsked, 1);
$eventManager->attach('bye', $onGoodbye);

/**
 * Call created event
 * 
 * output:
 * Hi, Alice.
 * How are you?
 */
$eventManager->trigger($event, null, ['Alice']); // 'Alice' will be passed as argument to the listener callback

/**
 * Create new event and call it
 * 
 * output:
 * Bye!
 */
$newEvent = $eventManager->trigger('bye');

With the stopPropagation() method, you can stop calling the remaining listeners

Event stop propagation example:

$eventManager = new EventManager;

$helloWorld = function() {
    echo "Hello world!";
};

$eventManager->attach('hello.world', $helloWorld);

$event = $eventManager->trigger('hello.world');
$event->stopPropagation();
// It will not work
$event = $eventManager->trigger('hello.world');

License: MIT