Created
April 3, 2015 21:36
-
-
Save eXeDK/45850b62ae29afd8dac6 to your computer and use it in GitHub Desktop.
EventHandler class
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
require_once 'EventPriorityQueue.php'; | |
/** | |
* Class EventHandler | |
*/ | |
class EventHandler { | |
/** | |
* Holds all events in an array of EventPriorityQueues | |
* | |
* @var EventPriorityQueue[] | |
*/ | |
private static $events = []; | |
/** | |
* Add an Event to a specific handle | |
* | |
* @param string $handle | |
* @param callable|Event $event | |
* @param int $priority | |
* | |
* @throws Exception If the type of the $event is not callable and not an Event, throws an Exception | |
*/ | |
public static function addEvent($handle, $event, $priority = 10) { | |
if ( ! array_key_exists($handle, self::$events)) { | |
self::$events[$handle] = new EventPriorityQueue(); | |
} | |
if ($event instanceof Event) { | |
self::$events[$handle]->insert($event, $priority); | |
} elseif (is_callable($event)) { | |
self::$events[$handle]->insert(new Event($event), $priority); | |
} else { | |
throw new Exception('Type of $event was unknown, it was: ' . gettype($event)); | |
} | |
} | |
/** | |
* Execute all events for the specific handle | |
* | |
* @param string $handle | |
*/ | |
public static function executeEvents($handle) { | |
if (array_key_exists($handle, self::$events)) { | |
/** | |
* @var $event Event | |
*/ | |
foreach (self::$events[$handle] as $event) { | |
$event->run(); | |
} | |
// Remove the handle from the array of events | |
unset(self::$events[$handle]); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment