0
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。

4

1 回答 1

0

您只需要更换:

$callback($eventName, $data);

$callback($data);

观看现场演示

于 2013-03-01T14:50:57.617 回答