Php/Smarty/MemcacheクラスSmarty3
class Smarty_CacheResource_Memcache extends Smarty_CacheResource_Custom
{
private $_m;
public function __construct($memcache)
{
$this->_m = $memcache;
}
protected function fetch($id, $name, $cache_id, $compile_id, &$content, &$mtime)
{
$key = md5($name . $cache_id . $compile_id);
$data = $this->_m->getCache($key);
if ($data === false) {
return false;
}
// 解凍
if (function_exists('gzuncompress')) {
$data = gzuncompress($data);
}
// mtime + content 分離
$pos = strpos($data, "\n");
if ($pos === false) {
return false;
}
$mtime = (int)substr($data, 0, $pos);
$content = substr($data, $pos + 1);
return true;
}
protected function save($id, $name, $cache_id, $compile_id, $exp_time, $content)
{
$key = md5($name . $cache_id . $compile_id);
// mtime + content
$data = time() . "\n" . $content;
// 圧縮
if (function_exists('gzcompress')) {
$data = gzcompress($data, 1); // 1が一番速い
}
return $this->_m->setCache($key, $data, $exp_time);
}
protected function delete($name, $cache_id, $compile_id, $exp_time)
{
$key = md5($name . $cache_id . $compile_id);
return $this->_m->delCache($key);
}
protected function purge()
{
return true;
}
}
呼び出し
require_once APPLICATION_PATH . '/models/MemcacheModel.php';
$cache = MemcacheModel::getInstance();
require_once APPLICATION_PATH . '/../library/Smarty_CacheResource_Memcache.php';
$this->registerCacheResource(
'memcache',
new Smarty_CacheResource_Memcache($cache)
);
$cacheのmemcacheはカスタマイズしてるので、それぞれの環境に合わせる。