Created
February 14, 2017 08:20
-
-
Save aambrozkiewicz/ca1c372fbb565a91d872bafd877780f2 to your computer and use it in GitHub Desktop.
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 | |
trait Observable | |
{ | |
protected $subscribers = []; | |
public function on($name, $fn) | |
{ | |
if (empty($this->subscribers[$name])) { | |
$this->subscribers[$name] = []; | |
} | |
$this->subscribers[$name][] = $fn; | |
return $this; | |
} | |
public function off($name, $fn) | |
{ | |
unset($this->subscribers[$name][array_search($fn, $this->subscribers[$name])]); | |
return $this; | |
} | |
public function fire($name, ...$params) | |
{ | |
$subscribers = array_filter($this->subscribers, function($eventName) use ($name) { | |
return fnmatch($eventName, $name); | |
}, ARRAY_FILTER_USE_KEY); | |
foreach ($subscribers as $eventName => $fns) { | |
foreach ($fns as $fn) { | |
$fn(...$params); | |
} | |
} | |
} | |
} | |
class Mediator | |
{ | |
use Observable; | |
} | |
$p = function() { echo 'a'; }; | |
$m = new Mediator; | |
$m->on('*.finish', $p); | |
$m->fire('uber.finish'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment