Skip to content

Instantly share code, notes, and snippets.

@krabello
Last active October 17, 2017 00:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save krabello/a25b114007c8742535a5bc80c8d90a32 to your computer and use it in GitHub Desktop.
Save krabello/a25b114007c8742535a5bc80c8d90a32 to your computer and use it in GitHub Desktop.
Event Dispatcher Example

Usage

$event = new SyncDispatcher;

$event->listen('subscribed', function () {
   echo 'handling it 1' . PHP_EOL;
});

$event->listen('un-subscribed', function () {
    echo 'un-subscribed it 1' . PHP_EOL;
});

$event->listen('subscribed', function () {
    echo 'handling it 2' . PHP_EOL;
});

$event->fire('subscribed');
$event->fire('un-subscribed');
<?php
/**
* Interface EventDispatcher
*/
interface EventDispatcher
{
/**
* @param $name
* @param $handler
*
* @return mixed
*/public function listen($name, $handler);
/**
* @param $name
*
* @return mixed
*/public function fire($name);
}
/**
* Class SyncDispatcher
*/
class SyncDispatcher implements EventDispatcher
{
/**
* @var array
*/
protected $events = [];
/**
* @param $name
* @param $handler
*
* @return void
*/
public function listen($name, $handler)
{
$this->events[$name][] = $handler;
}
/**
* @param $name
*
* @return bool
*/
public function fire($name)
{
if (!array_key_exists($name, $this->events)) {
return false;
}
foreach ($this->events[$name] as $event) {
$event();
}
return true;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment