這篇文章主要介紹了PHP實(shí)現(xiàn)事件機(jī)制的方法,實(shí)例分析了事件機(jī)制的原理與php的相關(guān)實(shí)現(xiàn)技巧,需要的朋友可以參考下
本文實(shí)例講述了PHP實(shí)現(xiàn)事件機(jī)制的方法。分享給大家供大家參考。具體分析如下:
內(nèi)置了事件機(jī)制的語(yǔ)言不多,php也沒(méi)有提供這樣的功能。事件(Event)說(shuō)簡(jiǎn)單了就是一個(gè)Observer模式,實(shí)現(xiàn)起來(lái)很容易。但是有所不同的是,事件的監(jiān)聽(tīng)者誰(shuí)都可以加,但是只能由直接包含它的對(duì)象觸發(fā)。這就有一點(diǎn)點(diǎn)難度了。php有一個(gè)debug_backtrace函數(shù),可以得到當(dāng)前的調(diào)用棧,由此可以找到判斷調(diào)用事件觸發(fā)函數(shù)的對(duì)象是不是直接包含它的對(duì)象的辦法。
- <?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);
- }
- }
- }
希望本文所述對(duì)大家的php程序設(shè)計(jì)有所幫助。
新聞熱點(diǎn)
疑難解答