. ** ** it_cache.class - Caching functions */ class it_cache { static $_fetch_func; static $_store_func; static function _defaults($p) { $p += array( 'ttl' => 2, 'distributed' => false, 'hostsfile' => '/opt/ultra/etc/memcached.hosts', ); if (!it::is_live()) $p['distributed'] = false; # Always local cache on non-live systems return $p; } /** * Get value for specific key from cache. Can be mixed value but no objects. * @param $key Key to get value for * @param $p['distributed'] Use distributed memcache [false] * @return Value for given key or null */ static function get($key, $p = array()) { $p = it_cache::_defaults($p); if ($result = $GLOBALS['it_cache_local'][$key]) ; # Use local copy else if ($p['distributed'] && ($memcache = it_cache::_get_memcache($p))) $result = @$memcache->get($key); else $result = ($func = self::$_fetch_func) ? $func($key) : null; return $result; } /** * Put value for specific key into cache. Can be mixed value but no objects. * @param $key Key to put value with * @param $value Value to put (mixed but no objects allowed) * @param $p['distributed'] Use distributed memcache [false] * @param $p['ttl'] Time to live for this key/value-pair in seconds * @return Returns $value */ static function put($key, $value, $p = array()) { $p = it_cache::_defaults($p); if ($p['distributed'] && ($memcache = it_cache::_get_memcache($p))) { $success = @$memcache->set($key, $value, MEMCACHE_COMPRESSED, $p['ttl']); } else { function_exists("eaccelerator_gc") && eaccelerator_gc(); $success = ($func = self::$_store_func) ? $func($key, $value, $p['ttl']) : null; } if (!$success) it::error(array('title' => ($p['distributed'] ? "memcache" : self::$_store_func) . " in it_cache::put failed for key '$key'", 'id' => "it_cache_put", 'graceperiod' => 60, 'timewindow' => 10)); $GLOBALS['it_cache_local'][$key] = $value; # Also store local copy return $value; } static function _get_memcache($p) { $memcache_id = "it_cache_memcache_" . $p['hostsfile']; if (!isset($GLOBALS[$memcache_id]) && class_exists("Memcache", false)) { $memcache = new Memcache; foreach (array_filter(it::replace(array('[#\s].*' => ""), file($p['hostsfile']))) as $host) $reachable += intval(@$memcache->addServer($host)); $GLOBALS[$memcache_id] = $reachable ? $memcache : false; } return $GLOBALS[$memcache_id]; } } it_cache::$_fetch_func = function_exists("apcu_fetch") ? "apcu_fetch" : (function_exists("apc_fetch") ? "apc_fetch" : (function_exists("eaccelerator_get") ? "eaccelerator_get" : null)); it_cache::$_store_func = function_exists("apcu_store") ? "apcu_store" : (function_exists("apc_store") ? "apc_store" : (function_exists("eaccelerator_put") ? "eaccelerator_put" : null)); ?>