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 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥15 网络通信安全解决方案
  • ¥50 yalmip+Gurobi
  • ¥20 win10修改放大文本以及缩放与布局后蓝屏无法正常进入桌面
  • ¥15 itunes恢复数据最后一步发生错误
  • ¥15 关于#windows#的问题:2024年5月15日的win11更新后资源管理器没有地址栏了顶部的地址栏和文件搜索都消失了
  • ¥100 H5网页如何调用微信扫一扫功能?
  • ¥15 讲解电路图,付费求解
  • ¥15 有偿请教计算电磁学的问题涉及到空间中时域UTD和FDTD算法结合的
  • ¥15 three.js添加后处理以后模型锯齿化严重