Files

102 lines
2.4 KiB
PHP
Raw Permalink Normal View History

2011-09-16 14:19:56 +00:00
<?php
/**
* Memcache CacheResource
* CacheResource Implementation based on the KeyValueStore API to use
* memcache as the storage resource for Smarty's output caching.
* Note that memcache has a limitation of 256 characters per cache-key.
* To avoid complications all cache-keys are translated to a sha1 hash.
*
2023-08-08 00:04:14 +02:00
* @author Rodney Rehm
2011-09-16 14:19:56 +00:00
*/
2023-08-08 00:04:14 +02:00
class Smarty_CacheResource_Memcache extends \Smarty\Cacheresource\KeyValueStore
2013-07-14 22:15:45 +00:00
{
2011-09-16 14:19:56 +00:00
/**
* memcache instance
*
2011-09-16 14:19:56 +00:00
* @var Memcache
*/
2023-08-08 00:04:14 +02:00
private $memcache = null;
2013-07-14 22:15:45 +00:00
2023-08-08 00:04:14 +02:00
/**
* @return Memcache|Memcached
*/
public function getMemcache() {
if ($this->memcache === null) {
if (class_exists('Memcached')) {
$this->memcache = new Memcached();
} else {
$this->memcache = new Memcache();
}
$this->memcache->addServer('127.0.0.1', 11211);
}
return $this->memcache;
}
2013-07-14 22:15:45 +00:00
2011-09-16 14:19:56 +00:00
/**
* Read values for a set of keys from cache
*
2018-06-12 09:58:15 +02:00
* @param array $keys list of keys to fetch
*
2013-07-14 22:15:45 +00:00
* @return array list of values with the given keys used as indexes
2011-09-16 14:19:56 +00:00
* @return boolean true on success, false on failure
*/
protected function read(array $keys)
{
$res = array();
foreach ($keys as $key) {
$k = sha1($key);
2023-08-08 00:04:14 +02:00
$res[$key] = $this->getMemcache()->get($k);
2011-09-16 14:19:56 +00:00
}
return $res;
2011-09-16 14:19:56 +00:00
}
2013-07-14 22:15:45 +00:00
2011-09-16 14:19:56 +00:00
/**
* Save values for a set of keys to cache
*
2018-06-12 09:58:15 +02:00
* @param array $keys list of values to save
* @param int $expire expiration time
*
2011-09-16 14:19:56 +00:00
* @return boolean true on success, false on failure
*/
protected function write(array $keys, $expire = null)
2011-09-16 14:19:56 +00:00
{
foreach ($keys as $k => $v) {
$k = sha1($k);
if (class_exists('Memcached')) {
2023-08-08 00:04:14 +02:00
$this->getMemcache()->set($k, $v, $expire);
} else {
2023-08-08 00:04:14 +02:00
$this->getMemcache()->set($k, $v, 0, $expire);
}
2011-09-16 14:19:56 +00:00
}
return true;
}
/**
* Remove values from cache
*
2018-06-12 09:58:15 +02:00
* @param array $keys list of keys to delete
*
2011-09-16 14:19:56 +00:00
* @return boolean true on success, false on failure
*/
protected function delete(array $keys)
{
foreach ($keys as $k) {
$k = sha1($k);
2023-08-08 00:04:14 +02:00
$this->getMemcache()->delete($k);
2011-09-16 14:19:56 +00:00
}
return true;
}
/**
* Remove *all* values from cache
*
* @return boolean true on success, false on failure
*/
protected function purge()
{
2023-08-08 00:04:14 +02:00
return $this->getMemcache()->flush();
2011-09-16 14:19:56 +00:00
}
}