基于PHP實現(xiàn)的事件機制實例分析
本文實例講述了基于PHP實現(xiàn)的事件機制。分享給大家供大家參考。具體分析如下:
內(nèi)置了事件機制的語言不多,php也沒有提供這樣的功能。事件(Event)說簡單了就是一個Observer模式,實現(xiàn)起來很容易。但是有所不同的是,事件的監(jiān)聽者誰都可以加,但是只能由直接包含它的對象觸發(fā)。這就有一點點難度了。php有一個debug_backtrace函數(shù),可以得到當(dāng)前的調(diào)用棧,由此可以找到判斷調(diào)用事件觸發(fā)函數(shù)的對象是不是直接包含它的對象的辦法。
<?php
/**
* 事件
*
* @author xiezhenye <xiezhenye@gmail.com>
* @since 2007-7-20
*/
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);
}
}
}
希望本文所述對大家的php程序設(shè)計有所幫助。
相關(guān)文章
php獲取數(shù)組中重復(fù)數(shù)據(jù)的兩種方法
兩天前,需要用到找出php數(shù)組中的重復(fù)數(shù)據(jù),總結(jié)了兩種方法,在這里跟大家共享一下,需要的朋友可以參考下2013-06-06
PHP Global變量定義當(dāng)前頁面的全局變量實現(xiàn)探討
我們在這篇文章中就針對PHP Global變量出現(xiàn)的問題給出了一些具體的解決辦法,感興趣的朋友可以參考下哈2013-06-06
php正則過濾html標(biāo)簽、空格、換行符的代碼(附說明)
最常用正則過濾代碼,能夠幫你過濾多余回車,注釋,html標(biāo)簽等。2010-10-10
php站內(nèi)搜索并高亮顯示關(guān)鍵字的實現(xiàn)代碼
將sql語句中包含的%$info%交給DBMS執(zhí)行的時候,他會查找字段中含有變量$info的值的信息2011-12-12
php set_time_limit()函數(shù)的使用詳解
本篇文章是對php中的set_time_limit()函數(shù)進行了詳細的分析介紹,需要的朋友參考下2013-06-06

