Home > Backend Development > PHP Tutorial > PHP实现事件机制实例分析_PHP

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

WBOY
Release: 2016-05-30 08:46:00
Original
847 people have browsed it

本文实例讲述了PHP实现事件机制的方法。分享给大家供大家参考。具体分析如下:

内置了事件机制的语言不多,php也没有提供这样的功能。事件(Event)说简单了就是一个Observer模式,实现起来很容易。但是有所不同的是,事件的监听者谁都可以加,但是只能由直接包含它的对象触发。这就有一点点难度了。php有一个debug_backtrace函数,可以得到当前的调用栈,由此可以找到判断调用事件触发函数的对象是不是直接包含它的对象的办法。

<&#63;php
/**
* 事件
*
* @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);
    }
  }
}

Copy after login

希望本文所述对大家的php程序设计有所帮助。

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template