duanniedang3946 2014-08-21 19:57
浏览 22
已采纳

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.

  • 写回答

1条回答 默认 最新

  • dongyi7669 2014-08-21 20:50
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)
  • ¥15 相敏解调 matlab
  • ¥15 求lingo代码和思路
  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应
  • ¥15 matlab基于pde算法图像修复,为什么只能对示例图像有效
  • ¥100 连续两帧图像高速减法
  • ¥15 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据