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');
它打印出“测试”,而不是 123。