PHP Classes
elePHPant
Icontem

File: tests/event_manager_tests.php

Recommend this page to a friend!
  Classes of Kiril Savchev  >  ITE Event Manager  >  tests/event_manager_tests.php  >  Download  
File: tests/event_manager_tests.php
Role: Example script
Content type: text/plain
Description: Example script
Class: ITE Event Manager
Manage events implementing PSR-14 interface
Author: By
Last change: Format to PSR2
Date: 3 years ago
Size: 1,833 bytes
 

 

Contents

Class file image Download
<?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");