Skip to content

Instantly share code, notes, and snippets.

@aambrozkiewicz
Created February 14, 2017 08:20
Show Gist options
  • Save aambrozkiewicz/ca1c372fbb565a91d872bafd877780f2 to your computer and use it in GitHub Desktop.
Save aambrozkiewicz/ca1c372fbb565a91d872bafd877780f2 to your computer and use it in GitHub Desktop.
<?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