class CacheService
{
protected $cache;
protected $tcache;
protected $all_info;
protected $prefix = '~aPd';
function __construct()
{
$toolkit = lmbToolkit :: instance();
$this->cache = $toolkit->createCacheConnectionByName('base');
$this->tcahce = new lmbTaggableCache($this->cache);
$this->all_info =
array(
'blog_main_page' => array(
'ttl' => 12*60*60,
'tags' => array('blog_message'),
'vars' => array('page', 'sort'),
),
'text_block' => array(
'ttl' => 24*60*60,
'tags' => array('text_block'),
'vars' => array('id'),
),
'comparison' => array(
'ttl' => 2*60*60,
'vars' => array('id'),
'tag_ids' => array('comparison' => 'id'),
),
'request_dispath' => array(
'ttl' => 7*24*60*60,
'vars' => array('path'),
),
);
}
function getCacheInfo($name, $vars)
{
if(!isset($this->all_info[$name]))
throw new Exception('Failed name cache!');
$raw_info = $this->all_info[$name];
$key = 'k'.$name;
if(isset($raw_info['vars']))
{
ksort($vars);
foreach($raw_info['vars'] as $vn)
if(isset($vars[$vn]))
$key .= $vn.'='.$vars[$vn].';';
else
throw new Exception('Not set var: '.$vn);
}
$info = array();
$info['key'] = $key;
$info['ttl'] = $raw_info['ttl'];
$info['tags'] = isset($raw_info['tags']) ? $raw_info['tags'] : array();
if(isset($raw_info['tag_ids']))
foreach($raw_info['tag_ids'] as $t => $v)
if(isset($vars[$v]))
$info['tags'][] = $t.'-id:'.$vars[$v];
else
throw new Exception('Not set var: '.$v);
$info['key'] = $this->prefix.$info['key'];
foreach($info['tags'] as $n => $v)
$info['tags'][$n] = $this->prefix.$v;
return $info;
}
function arChange($obj)
{
$this->_deleteByTagsForAr($obj);
}
function arDestroy($obj)
{
$this->_deleteByTagsForAr($obj);
}
protected function _deleteByTagsForAr($obj)
{
if(!is_string($obj))
{
$table = $obj->getTableName();
$this->tcahce->deleteByTag($this->prefix.$table);
if($obj->has('id'))
$this->tcahce->deleteByTag($this->prefix.$table.'-id:'.$obj->id);
}
else
$this->tcahce->deleteByTag($this->prefix.$obj);
}
function flushCache()
{
$this->cache->flush();
}
function callCache($name, $vars, $function, $params)
{
$info = $this->getCacheInfo($name, $vars);
if(null !== ($value = $this->tcahce->get($info['key'])))
return $value;
$value = call_user_func_array($function, $params);
if(!$value)
$value = false;
$this->tcahce->set($info['key'], $value, $info['ttl'], $info['tags']);
return $value;
}
}