4 * Memcache CacheResource
6 * CacheResource Implementation based on the KeyValueStore API to use
7 * memcache as the storage resource for Smarty's output caching.
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.
12 * @package CacheResource-examples
15 class Smarty_CacheResource_Memcache
extends Smarty_CacheResource_KeyValueStore
{
20 protected $memcache = null;
22 public function __construct()
24 $this->memcache
= new Memcache();
25 $this->memcache
->addServer( '127.0.0.1', 11211 );
29 * Read values for a set of keys from cache
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
35 protected function read(array $keys)
37 $_keys = $lookup = array();
38 foreach ($keys as $k) {
44 $res = $this->memcache
->get($_keys);
45 foreach ($res as $k => $v) {
46 $_res[$lookup[$k]] = $v;
52 * Save values for a set of keys to cache
54 * @param array $keys list of values to save
55 * @param int $expire expiration time
56 * @return boolean true on success, false on failure
58 protected function write(array $keys, $expire=null)
60 foreach ($keys as $k => $v) {
62 $this->memcache
->set($k, $v, 0, $expire);
68 * Remove values from cache
70 * @param array $keys list of keys to delete
71 * @return boolean true on success, false on failure
73 protected function delete(array $keys)
75 foreach ($keys as $k) {
77 $this->memcache
->delete($k);
83 * Remove *all* values from cache
85 * @return boolean true on success, false on failure
87 protected function purge()
89 return $this->memcache
->flush();