基于PHP實(shí)現(xiàn)的事件機(jī)制實(shí)例分析
本文實(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>
* @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);
}
}
}
希望本文所述對(duì)大家的php程序設(shè)計(jì)有所幫助。
相關(guān)文章
PHP簡(jiǎn)單實(shí)現(xiàn)無(wú)限級(jí)分類(lèi)的方法
這篇文章主要介紹了PHP簡(jiǎn)單實(shí)現(xiàn)無(wú)限級(jí)分類(lèi)的方法,涉及sql語(yǔ)句及遞歸調(diào)用的相關(guān)技巧,需要的朋友可以參考下2016-05-05
php jquery 實(shí)現(xiàn)新聞標(biāo)簽分類(lèi)與無(wú)刷新分頁(yè)
php + jquery ui插件 + jquery pager插件 實(shí)現(xiàn)新聞的 標(biāo)簽分類(lèi) + 無(wú)刷新分頁(yè)2009-12-12
PHP實(shí)現(xiàn)時(shí)間日期友好顯示實(shí)現(xiàn)代碼
之前腳本之家小編也為大家分享過(guò)類(lèi)似的時(shí)間日期顯示代碼,這里為大家分享的更加友好,大家根據(jù)說(shuō)明調(diào)用即可2019-09-09
使用PHP連接多種數(shù)據(jù)庫(kù)的實(shí)現(xiàn)代碼(mysql,access,sqlserver,Oracle)
我們今天為大家介紹的PHP連接數(shù)據(jù)庫(kù)的方法包括在MYSQL數(shù)據(jù)庫(kù)、ACCESS數(shù)據(jù)庫(kù)、MS SQL數(shù)據(jù)庫(kù)和Oracle數(shù)據(jù)庫(kù)中實(shí)現(xiàn)2016-12-12
PHP簡(jiǎn)單實(shí)現(xiàn)歐拉函數(shù)Euler功能示例
這篇文章主要介紹了PHP簡(jiǎn)單實(shí)現(xiàn)歐拉函數(shù)Euler功能,簡(jiǎn)單說(shuō)明了歐拉函數(shù)的概念、原理,并結(jié)合實(shí)例形式分析了php實(shí)現(xiàn)歐拉函數(shù)的相關(guān)操作技巧,需要的朋友可以參考下2017-11-11
PHP浮點(diǎn)數(shù)的一個(gè)常見(jiàn)問(wèn)題
本文主要給大家詳細(xì)介紹了下php的浮點(diǎn)數(shù),以及在應(yīng)用中關(guān)于浮點(diǎn)數(shù)的一個(gè)小問(wèn)題,有需要的小伙伴可以參考下2016-03-03

