Php/Smarty/MemcacheクラスSmarty3

提供: 初心者エンジニアの簡易メモ
ナビゲーションに移動 検索に移動
<?php
class Smarty_CacheResource_Memcache extends Smarty_CacheResource_KeyValueStore
{
    private $memcache;

    public function __construct($memcache)
    {
        $this->memcache = $memcache;
    }

    protected function read(array $keys)
    {
        $result = [];
        foreach ($keys as $key) {
            $zendKey = md5($key);
            $data = $this->memcache->getCache($zendKey);
            if ($data !== false) {
                $result[$key] = $data;
            }
        }
        return $result;
    }

    protected function write(array $keys, $expire = null)
    {
        foreach ($keys as $key => $value) {
            $zendKey = md5($key);
            $this->memcache->setCache(
                $zendKey,
                $value,
                $expire
            );
        }
        return true;
    }

    protected function delete(array $keys)
    {
        foreach ($keys as $key) {
            $zendKey = $this->normalizeKey($key);
            $this->memcache->delCache($zendKey);
        }
        return true;
    }

    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はカスタマイズしてるので、それぞれの環境に合わせる。