Skip to content

Instantly share code, notes, and snippets.

@colynb
Created April 28, 2017 01:03
Show Gist options
  • Save colynb/2ea14e99ccb54102f6a56ad7190ca03d to your computer and use it in GitHub Desktop.
Save colynb/2ea14e99ccb54102f6a56ad7190ca03d to your computer and use it in GitHub Desktop.
Simple PHP event handling class
<?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;
}
}
@colynb
Copy link
Author

colynb commented Apr 28, 2017

Examples

class SendNewUserNotification
{
    /**
     * @param $eventName
     * @param null $user
     */
    public function handle($eventName, $user = null)
    {
        var_dump($eventName, $user);
        // @todo send user to gateway
    }
}

FSBOEvent::on('user.registered', new SendNewUserNotification);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment