class Mediator {
protected $events = array();
public function attach($eventName, $callback) {
if (!isset($this->events[$eventName])) {
$this->events[$eventName] = array();
}
$this->events[$eventName][] = $callback;
}
public function trigger($eventName, $data = null) {
foreach ($this->events[$eventName] as $callback) {
$callback($eventName, $data);
}
}
}
$mediator = new Mediator;
$mediator->attach('stop', function() { echo "Stopping"; });
$mediator->attach('stop', function() { echo "Stopped"; });
$mediator->trigger('stop'); // prints "StoppingStopped"
我无法弄清楚如何成功地将数据传递给模式,即我想传递数据库对象,但它最终会像这样。
$mediator->attach('test', function($test) { echo $test; });
$mediator->trigger('test', '123');
打印出“test”,而不是123.