I built the below to achieve some very basic event handling functionality. However, I would like to review some other as well. So if you would like to share your own interpretation and/or solution for handling events in PHP it would be appreciated. Pretty much just looking for some insight and discussion regarding handling events and classes designed to achieve such a task in PHP. I’m not really looking for anything just thrown together but solutions that have been clearly thought through for a particular requirement or application.
thanks
<?php
/*
* Manages events
*/
class EventHandler {
private
/*
* Stack of object hashes with event keys
* and associated handlers to each event.
*/
$_arrEvents;
public function __construct() {
$this->_init();
}
private function _init() {
$this->_arrEvents = array();
}
/*
* Get objects unique foorprint for reference in events array
*
* @param obj object to get unique foot print for
* @return str unique object foot print
*/
private function _getFootprint($obj) {
return spl_object_hash($obj);
}
/*
* Subscribe handler to event for object
*
* @param obj listen to this object
* @param str for this event
* @param arr [obj,method] call this handler on event
*/
public function subscribe($objDispatcher,$strEvt,$arrHandler) {
$strFootprint = $this->_getFootprint($objDispatcher);
$this->_arrEvents[$strFootprint][$strEvt][] = $arrHandler;
}
/*
* Fire event
*
* @param obj target
* @param str event name
*/
public function fire($objTarget,$strEvt) {
$strTarget = $this->_getFootprint($objTarget);
if(isset($this->_arrEvents[$strTarget],$this->_arrEvents[$strTarget][$strEvt])) {
/*
* Call event listeners
*/
foreach($this->_arrEvents[$strTarget][$strEvt] as $arrHandler) {
array_shift($arrHandler)->{array_shift($arrHandler)}(array('target'=>$objTarget,'event'=>$strEvt));
}
/*
* Bubble event
*/
foreach($this->_arrEvents[$strTarget][$strEvt] as $arrHandler) {
$this->fire(array_shift($arrHandler),$strEvt);
}
}
}
}
?>