]> git.mxchange.org Git - friendica.git/blob - library/Smarty/demo/plugins/cacheresource.memcache.php
Merge remote branch 'upstream/master'
[friendica.git] / library / Smarty / demo / plugins / cacheresource.memcache.php
1 <?php
2
3 /**
4  * Memcache CacheResource
5  *
6  * CacheResource Implementation based on the KeyValueStore API to use
7  * memcache as the storage resource for Smarty's output caching.
8  *
9  * Note that memcache has a limitation of 256 characters per cache-key.
10  * To avoid complications all cache-keys are translated to a sha1 hash.
11  *
12  * @package CacheResource-examples
13  * @author Rodney Rehm
14  */
15 class Smarty_CacheResource_Memcache extends Smarty_CacheResource_KeyValueStore {
16     /**
17      * memcache instance
18      * @var Memcache
19      */
20     protected $memcache = null;
21     
22     public function __construct()
23     {
24         $this->memcache = new Memcache();
25         $this->memcache->addServer( '127.0.0.1', 11211 );
26     }
27     
28     /**
29      * Read values for a set of keys from cache
30      *
31      * @param array $keys list of keys to fetch
32      * @return array list of values with the given keys used as indexes
33      * @return boolean true on success, false on failure
34      */
35     protected function read(array $keys)
36     {
37         $_keys = $lookup = array();
38         foreach ($keys as $k) {
39             $_k = sha1($k);
40             $_keys[] = $_k;
41             $lookup[$_k] = $k;
42         }
43         $_res = array();
44         $res = $this->memcache->get($_keys);
45         foreach ($res as $k => $v) {
46             $_res[$lookup[$k]] = $v;
47         }
48         return $_res;
49     }
50     
51     /**
52      * Save values for a set of keys to cache
53      *
54      * @param array $keys list of values to save
55      * @param int $expire expiration time
56      * @return boolean true on success, false on failure
57      */
58     protected function write(array $keys, $expire=null)
59     {
60         foreach ($keys as $k => $v) {
61             $k = sha1($k);
62             $this->memcache->set($k, $v, 0, $expire);
63         }
64         return true;
65     }
66
67     /**
68      * Remove values from cache
69      *
70      * @param array $keys list of keys to delete
71      * @return boolean true on success, false on failure
72      */
73     protected function delete(array $keys)
74     {
75         foreach ($keys as $k) {
76             $k = sha1($k);
77             $this->memcache->delete($k);
78         }
79         return true;
80     }
81
82     /**
83      * Remove *all* values from cache
84      *
85      * @return boolean true on success, false on failure
86      */
87     protected function purge()
88     {
89         return $this->memcache->flush();
90     }
91 }