Created
April 28, 2017 01:03
-
-
Save colynb/2ea14e99ccb54102f6a56ad7190ca03d to your computer and use it in GitHub Desktop.
Simple PHP event handling class
This file contains hidden or 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 | |
namespace Events; | |
class FSBOEvent | |
{ | |
/** | |
* @var array | |
*/ | |
protected static $eventHandlers = []; | |
/** | |
* @param $eventName | |
* @param $payload | |
* @return null | |
* @usage FSBOEvent::trigger('user.created', $userObject) | |
*/ | |
public static function trigger($eventName, $payload) | |
{ | |
if ( ! key_exists($eventName, self::$eventHandlers) ) { | |
return null; | |
} | |
foreach (self::$eventHandlers[$eventName] as $handler) { | |
$handler->handle($eventName, $payload); | |
} | |
} | |
/** | |
* @param $eventName | |
* @param $handler | |
* @usage FSBOEvent::on('user.created', Listeners\ExampleUserListener) | |
*/ | |
public static function on($eventName, $handler) | |
{ | |
if ( ! key_exists($eventName, self::$eventHandlers) ) { | |
self::$eventHandlers[$eventName] = []; | |
} | |
self::$eventHandlers[$eventName][] = $handler; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Examples