From 5853097561cddd1a2405ac9d9b9659ca8772cc5e Mon Sep 17 00:00:00 2001 From: elij Date: Sun, 29 May 2011 23:27:55 +0200 Subject: Make cache type selectable based on config value Provie a mechanism to specify cache type from NONE, APC, or MEMCACHE based on a config variable. If MEMCACHE type is selected, a list of servers can be specified to provide multiserver support. Note that php-memcaced is required for MEMCACHE support. Lukas: Minor commenting style fixes. Signed-off-by: Lukas Fleischer --- web/lib/cachefuncs.inc.php | 82 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 82 insertions(+) create mode 100644 web/lib/cachefuncs.inc.php (limited to 'web/lib/cachefuncs.inc.php') diff --git a/web/lib/cachefuncs.inc.php b/web/lib/cachefuncs.inc.php new file mode 100644 index 00000000..3485b013 --- /dev/null +++ b/web/lib/cachefuncs.inc.php @@ -0,0 +1,82 @@ +addServer($mcserver[0], intval($mcserver[1])); + } +} + +# Set a value in the cache (currently APC) if cache is available for use. If +# not available, this becomes effectively a no-op (return value is +# false). Accepts an optional TTL (defaults to 600 seconds). +function set_cache_value($key, $value, $ttl=600) { + $status = false; + if (defined('EXTENSION_LOADED_APC')) { + $status = apc_store(CACHE_PREFIX.$key, $value, $ttl); + } + if (defined('EXTENSION_LOADED_MEMCACHE')) { + global $memcache; + $status = $memcache->set(CACHE_PREFIX.$key, $value, $ttl); + } + return $status; +} + +# Get a value from the cache (currently APC) if cache is available for use. If +# not available, this returns false (optionally sets passed in variable $status +# to false, much like apc_fetch() behaves). This allows for testing the fetch +# result appropriately even in the event that a 'false' value was the value in +# the cache. +function get_cache_value($key, &$status=false) { + if(defined('EXTENSION_LOADED_APC')) { + $ret = apc_fetch(CACHE_PREFIX.$key, $status); + if ($status) { + return $ret; + } + } + if (defined('EXTENSION_LOADED_MEMCACHE')) { + global $memcache; + $ret = $memcache->get(CACHE_PREFIX.$key); + if (!$ret) { + $status = false; + } + else { + $status = true; + } + return $ret; + } + return $status; +} + +# Run a simple db query, retrieving and/or caching the value if APC is +# available for use. Accepts an optional TTL value (defaults to 600 seconds). +function db_cache_value($dbq, $dbh, $key, $ttl=600) { + $status = false; + $value = get_cache_value($key, $status); + if (!$status) { + $result = db_query($dbq, $dbh); + $row = mysql_fetch_row($result); + $value = $row[0]; + set_cache_value($key, $value, $ttl); + } + return $value; +} + +?> -- cgit v1.2.3-24-g4f1b