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.
10 * @package CacheResource-examples
13 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
33 * @return array list of values with the given keys used as indexes
34 * @return boolean true on success, false on failure
36 protected function read(array $keys)
38 $_keys = $lookup = array();
39 foreach ($keys as $k) {
45 $res = $this->memcache->get($_keys);
46 foreach ($res as $k => $v) {
47 $_res[$lookup[$k]] = $v;
54 * Save values for a set of keys to cache
56 * @param array $keys list of values to save
57 * @param int $expire expiration time
59 * @return boolean true on success, false on failure
61 protected function write(array $keys, $expire = null)
63 foreach ($keys as $k => $v) {
65 $this->memcache->set($k, $v, 0, $expire);
72 * Remove values from cache
74 * @param array $keys list of keys to delete
76 * @return boolean true on success, false on failure
78 protected function delete(array $keys)
80 foreach ($keys as $k) {
82 $this->memcache->delete($k);
89 * Remove *all* values from cache
91 * @return boolean true on success, false on failure
93 protected function purge()
95 $this->memcache->flush();