0
votes

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.

1
How it is implemented in PrestaShop: model classes have Hook:exec('eventName') functions inside various methods (add, delete, .etc). Hook::exec looks up what other objects (class) are listening to this event (are registered to this event). Then a list of listener object classes are retrieved from this table and a method is called for each listener class (if is_callable) -> hookActionName. - gskema
This is easy to keep track of, simply make a class that has two methods, a register function that takes a callable and an event, and a notify event that takes an event and loops over the registered callables and calls them. - scragar
Both seem viable solutions. Thanks, point is indeed to remove the dependencies from the observed object. Creating an intermediary class to manage the subscriptions could do that. - html_programmer

1 Answers

1
votes

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.