| 
<?php
class CachedDB extends Database {
 
 var $is_cached = null;
 var $cache_id  = '';
 
 function CachedDB($config = 'default'){
 parent::Database($config);
 global $cfg_resource;
 $this->_connection['cache_ttl']    = $cfg_resource[$config]['cache_ttl']? intval($cfg_resource[$config]['cache_ttl']) : 0;
 $this->_connection['cache_path']   = $cfg_resource[$config]['cache_path']? $cfg_resource[$config]['cache_path'] : '';
 $this->_connection['cache_prefix'] = $cfg_resource[$config]['cache_prefix']? $cfg_resource[$config]['cache_prefix'] : 'db_';
 }
 
 /**
 * Check is the Database object is cached and not expired
 *
 * @param string $sql sql query
 * @return boolean true|false
 */
 function is_cached ($sql){
 $this->cache_id = $this->_connection['cache_path'] . $this->_connection['cache_prefix'] . md5($sql);
 //is it cached?
 if($this->cached) return true;
 //is it not cached?
 if($this->_connection['cache_ttl'] <= 0 or !file_exists($this->cache_id)) return false;
 //is it expired?
 if(!($mtime = filemtime($this->cache_id))) return false;
 if(($mtime + $this->_connection['cache_ttl']) < time()) {
 //erase the cached template
 @unlink($this->cache_id);
 return false;
 } else {
 //cache the result of is_cached() call
 $this->cached = true;
 return true;
 }
 }
 
 /**
 * Reimplement the query method with caching system
 *
 * @param string $sql sql query
 * @return integer number of affected rows
 */
 function query($sql, $ttl=''){
 if($ttl>0)
 $this->_connection['cache_ttl'] = $ttl;
 $return = 0;
 if($this->is_cached($sql)){
 //try to load object from disk
 $vars = unserialize(file_get_contents($this->cache_id));
 foreach($vars as $key=>$val)
 eval("$"."this->$key = $"."vars['"."$key'];");
 $return = $this->affected_rows;
 }else{
 //execute the query
 $return = parent::query($sql);
 //try to save it to disk
 if($f = @fopen($this->cache_id,"w")){
 $arr_tmp = array(
 'results' => $this->results,
 'metadata' => $this->metadata,
 'insert_id' => $this->insert_id,
 'affected_rows' => $this->affected_rows,
 );
 @fwrite($f,serialize($arr_tmp));
 @fclose($f);
 }else{
 $this->error('Could not save db cache file');
 }
 }
 return $return;
 }
 }
 ?>
 |