PHP观察者模式

PHP观察者模式

问题描述:

I just read a bit about the observer pattern in PHP.

I've read somewhere that the observed object should not be responsible for notifying the different observing objects, but rather the observed object should emit a single event to which the observing objects subscribe.
This way, the observed object does not need to keep track of the different observers, but rather should the observing objects register to the event.

Is there a way to achieve this in PHP?
I've read that the current way of implementing, is that the observed object keeps a reference to a dynamic array of observers.
It is not a problem, I just wonder if in PHP, something like an 'event emitter' exists.

我刚刚读了一下PHP中的观察者模式。 p>

我在某处读过,观察对象不应该负责通知不同的观察对象,而是观察对象应该发出观察对象所订阅的单个事件。 > 这样,观察对象不需要跟踪不同的观察者,而是观察对象应该注册到事件。 p>

有没有办法在PHP中实现这一点?
我已经读过当前实现的方法,就是被观察对象保持对动态观察者数组的引用 。 这不是问题,我只是想知道在PHP中是否存在类似“事件发射器”的东西。 p> div>

Both solutions in the comments are the same, just phrased differently.

class Observer {
    static protected $events = array();
    static public function register($callable, $event){
        if (!isset(self::$events[$event])) {
            self::$events[$event] = array();
        }
        self::$events[$event][] = $callable;
    }
    static public function notify($event, $params = array()) {
        if (isset(self::$events[$event])) {
            foreach (self::$events[$event] AS $callable){
                call_user_func_array($callable, $params);
            }
        }
    }
}

function print_meta($p1, $p2) {
    echo $p1 . ' ' . $p2 . PHP_EOL;
}

function multiply_meta($p1, $p2) {
    echo $p1 * $p2 . PHP_EOL;
}

function add_meta($p1, $p2) {
    echo $p1 + $p2 . PHP_EOL;
}

Observer::register('print_meta', 'event1');
Observer::register('multiply_meta', 'event1');

Observer::register('print_meta', 'event2');
Observer::register('add_meta', 'event2');

Observer::register('multiply_meta', 'event3');
Observer::register('add_meta', 'event3');

echo "Notifying of event 1" . PHP_EOL;
Observer::notify('event1', array(1, 2));
echo "Notifying of event 2" . PHP_EOL;
Observer::notify('event2', array(3, 4));
echo "Notifying of event 3" . PHP_EOL;
Observer::notify('event3', array(5, 6));

http://3v4l.org/Ov24F

Play around with the concept, you'll get the hang of it pretty quickly.