• PHP实现事件机制实例分析


    PHP实现事件机制实例分析


    内置了事件机制的语言不多,php也没有提供这种功能。事件(Event)说简单了就是一个Observer模式。实现起来非常easy。可是有所不同的是,事件的监听者谁都能够加,可是仅仅能由直接包括它的对象触发。

    这就有一点点难度了。php有一个debug_backtrace函数,能够得到当前的调用栈,由此能够找到推断调用事件触发函数的对象是不是直接包括它的对象的办法。

    <?php
    /**
    * 事件
    * @edit http://www.lai18.com 
    * @author xiezhenye <xiezhenye@gmail.com>
    */
    class Event {
      private $callbacks = array();
      private $holder;
      function __construct() {
        $bt = debug_backtrace();
        if (count($bt) < 2) {
          $this->holder = null;
          return;
        }
        $this->holder = &$bt[1]['object'];
      }
      function attach() {
        $args = func_get_args();
        switch (count($args)) {
          case 1:
            if (is_callable($args[0])) {
              $this->callbacks[]= $args[0];
              return;
            }
            break;
          case 2:
            if (is_object($args[0]) && is_string($args[1])) {
              $this->callbacks[]= array(&$args[0], $args[1]);
            }
            return;
          default:
            return;
        }
      }
      function notify() {
        $bt = debug_backtrace();
        if ($this->holder && 
            ((count($bt) >= 2 && $bt[count($bt) - 1]['object'] !== $this->holder)
            || (count($bt) < 2))) {
          throw(new Exception('Notify can only be called in holder'));
        }
        foreach ($this->callbacks as $callback) {
          $args = func_get_args();
          call_user_func_array($callback, $args);
        }
      }
    }
  • 相关阅读:
    华为云-Centos7.6-部署elasticSearch7.7
    linux下安装nginx
    Redis5.0.8集群安装
    redis5.0.8单机安装
    Mybatis打印SQL
    PostgreSQL新手教程
    Debian install jdk7
    Debian install jre7
    Debian /etc/apt/sources.list
    安装J2EE的SDK报错:could not find the required version of the Java(TM)2 Runtime Environment in '(null)'的解决办法。
  • 原文地址:https://www.cnblogs.com/brucemengbm/p/7039927.html
Copyright © 2020-2023  润新知