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 if (class_exists('Memcached')) {
25 $this->memcache = new Memcached();
27 $this->memcache = new Memcache();
29 $this->memcache->addServer('127.0.0.1', 11211);
33 * Read values for a set of keys from cache
35 * @param array $keys list of keys to fetch
37 * @return array list of values with the given keys used as indexes
38 * @return boolean true on success, false on failure
40 protected function read(array $keys)
42 $_keys = $lookup = array();
43 foreach ($keys as $k) {
49 $res = $this->memcache->get($_keys);
50 foreach ($res as $k => $v) {
51 $_res[ $lookup[ $k ] ] = $v;
58 * Save values for a set of keys to cache
60 * @param array $keys list of values to save
61 * @param int $expire expiration time
63 * @return boolean true on success, false on failure
65 protected function write(array $keys, $expire = null)
67 foreach ($keys as $k => $v) {
69 $this->memcache->set($k, $v, 0, $expire);
76 * Remove values from cache
78 * @param array $keys list of keys to delete
80 * @return boolean true on success, false on failure
82 protected function delete(array $keys)
84 foreach ($keys as $k) {
86 $this->memcache->delete($k);
93 * Remove *all* values from cache
95 * @return boolean true on success, false on failure
97 protected function purge()
99 $this->memcache->flush();