From be30e42c7430ad6ee54c0577ef688fe83ed78a4a Mon Sep 17 00:00:00 2001 From: Urban Müller Date: Thu, 27 Nov 2008 16:13:42 +0000 Subject: memory cache --- it_cache.class | 98 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 98 insertions(+) create mode 100644 it_cache.class (limited to 'it_cache.class') diff --git a/it_cache.class b/it_cache.class new file mode 100644 index 0000000..551d103 --- /dev/null +++ b/it_cache.class @@ -0,0 +1,98 @@ +. +** +** it_cache.class - Caching functions +*/ + +class it_cache +{ + +function _defaults($p) +{ + $p += array( + 'ttl' => 2, + 'distributed' => false, + 'hostsfile' => '/opt/ultra/etc/memcached.hosts', + ); + + return $p; +} + +/** + * Get value for specific key from cache. Can be mixed value but no objects. + * @param $key Key to get value for + * @return Value for given key or null + */ +function get($key, $p = array()) +{ + $p = it_cache::_defaults($p); + + if ($p['distributed'] && ($memcache = it_cache::_get_memcache($p))) + $result = @$memcache->get($key); + else + $result = function_exists("eaccelerator_get") ? eaccelerator_get($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['ttl'] Time to live for this key/value-pair + * @return Boolean if value was put into cache + */ +function put($key, $value, $p = array()) +{ + $p = it_cache::_defaults($p); + + if ($p['distributed'] && ($memcache = it_cache::_get_memcache($p))) + { + @$memcache->set($key, $value, 0, $p['ttl']); + } + else + { + function_exists("eaccelerator_gc") && eaccelerator_gc(); + $result = function_exists("eaccelerator_put") ? eaccelerator_put($key, $value, $p['ttl']) : null; + } + + return $result; +} + +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, 11211, true, 1, 1, -1)); + + $GLOBALS[$memcache_id] = $reachable ? $memcache : false; + } + + return $GLOBALS[$memcache_id]; +} + +} + +?> -- cgit v1.2.3