PHP
14 Feb 2010
 
 
 
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
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;
}
}