$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');
Last active
October 17, 2017 00:45
-
-
Save krabello/a25b114007c8742535a5bc80c8d90a32 to your computer and use it in GitHub Desktop.
Event Dispatcher Example
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 | |
/** | |
* 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