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