介体模式传递数据PHP

时间:2013-03-01 14:32:23

标签: php

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.

1 个答案:

答案 0 :(得分:0)

您只需要替换:

$callback($eventName, $data);

$callback($data);

See Live Demo