git-interface: Add test suite and basic tests
[aur.git] / web / lib / cachefuncs.inc.php
blobd558be44ee2040d0196af1f94329c8c0f8d05557
1 <?php
3 if (!defined('CACHE_TYPE')) {
4 define('CACHE_TYPE', 'NONE');
7 # Check if APC extension is loaded, and set cache prefix if it is.
8 if (CACHE_TYPE == 'APC' && !defined('EXTENSION_LOADED_APC')) {
9 define('EXTENSION_LOADED_APC', extension_loaded('apc'));
10 define('CACHE_PREFIX', 'aur:');
13 # Check if memcache extension is loaded, and set cache prefix if it is.
14 if (CACHE_TYPE == 'MEMCACHE' && !defined('EXTENSION_LOADED_MEMCACHE')) {
15 define('EXTENSION_LOADED_MEMCACHE', extension_loaded('memcached'));
16 define('CACHE_PREFIX', 'aur:');
17 global $memcache;
18 $memcache = new Memcached();
19 $mcs = defined('MEMCACHE_SERVERS') ? MEMCACHE_SERVERS : '127.0.0.1:11211';
20 foreach (explode(',', $mcs) as $elem) {
21 $telem = trim($elem);
22 $mcserver = explode(':', $telem);
23 $memcache->addServer($mcserver[0], intval($mcserver[1]));
27 # Set a value in the cache (currently APC) if cache is available for use. If
28 # not available, this becomes effectively a no-op (return value is
29 # false). Accepts an optional TTL (defaults to 600 seconds).
30 function set_cache_value($key, $value, $ttl=600) {
31 $status = false;
32 if (defined('EXTENSION_LOADED_APC')) {
33 $status = apc_store(CACHE_PREFIX.$key, $value, $ttl);
35 if (defined('EXTENSION_LOADED_MEMCACHE')) {
36 global $memcache;
37 $status = $memcache->set(CACHE_PREFIX.$key, $value, $ttl);
39 return $status;
42 # Get a value from the cache (currently APC) if cache is available for use. If
43 # not available, this returns false (optionally sets passed in variable $status
44 # to false, much like apc_fetch() behaves). This allows for testing the fetch
45 # result appropriately even in the event that a 'false' value was the value in
46 # the cache.
47 function get_cache_value($key, &$status=false) {
48 if(defined('EXTENSION_LOADED_APC')) {
49 $ret = apc_fetch(CACHE_PREFIX.$key, $status);
50 if ($status) {
51 return $ret;
54 if (defined('EXTENSION_LOADED_MEMCACHE')) {
55 global $memcache;
56 $ret = $memcache->get(CACHE_PREFIX.$key);
57 if (!$ret) {
58 $status = false;
60 else {
61 $status = true;
63 return $ret;
65 return $status;
68 # Run a simple db query, retrieving and/or caching the value if APC is
69 # available for use. Accepts an optional TTL value (defaults to 600 seconds).
70 function db_cache_value($dbq, $key, $ttl=600) {
71 $dbh = DB::connect();
72 $status = false;
73 $value = get_cache_value($key, $status);
74 if (!$status) {
75 $result = $dbh->query($dbq);
76 $row = $result->fetch(PDO::FETCH_NUM);
77 $value = $row[0];
78 set_cache_value($key, $value, $ttl);
80 return $value;