<?php
use Ite\EventManager\Event;
use Ite\EventManager\EventManager;
chdir(realpath(__DIR__ . '/..'));
require_once './vendor/autoload.php';
// load psr interfaces if they not exists
// (not part of this package, but included for convenience):
if (!interface_exists('Psr\\EventManager\\EventInterface')) {
require_once './psr/event-manager/EventInterface.php';
}
if (!interface_exists('Psr\\EventManager\\EventManagerInterface')) {
require_once './psr/event-manager/EventManagerInterface.php';
}
# Create some callbacks:
$callback1 = function(Event $e) {
echo $e->getName() . PHP_EOL;
};
$callback2 = function (Event $e) {
var_dump($e->getParams());
// return result to the trigger
return 1;
};
$callback3 = function (Event $e, $result) {
// get the result, returned by the events and dump it:
var_dump($result);
// This callback will stop the event triggering
$e->stopPropagation(1);
};
$callback4 = function (Event $e) {
var_dump($e);
};
// initiate the event manager
$eventManager = new EventManager();
// attach the callbacks:
$eventManager->attach('TestEvent', $callback1);
$eventManager->attach('TestEvent', $callback2);
$eventManager->attach('TestEvent', $callback3);
$eventManager->attach('TestEvent', $callback4);
// trigger the TestEvent. After $callback3 the triggering will be stopped
// and $callback4 won't be called:
$eventManager->trigger('TestEvent', null, ['a' => 1, 'b' => 2]);
// remove $callback3
$eventManager->detach('TestEvent', $callback3);
// trigger the TestEvent again. This time $callback4 will be called:
$eventManager->trigger('TestEvent', null, ['a' => 1, 'b' => 2]);
// attach to second event:
$eventManager->attach("Event2", $callback1);
$eventManager->attach("Event2", $callback4);
// trigger the second event:
$eventManager->trigger("Event2");
|