第1个回答 2016-12-18
用mac 做开发环境,封装 Cache,在没用 memcache 扩展的时候,使用 Cache 的时候,使用 file 替代。再生产环境的时候,如果有装 memcache 会自动切换。
class TL_Cache
{
private $_file;
private $_md5_key;
private $_md5_val = '';
private $_mem;
function __construct($key)
{
$this->_md5_key = $key;
//$ever = 'var'.DIRECTORY_SEPARATOR.'cache'.DIRECTORY_SEPARATOR.'.ever';
$ever = 'var'.DIRECTORY_SEPARATOR.'cache'.DIRECTORY_SEPARATOR.'data';
$ever .= DIRECTORY_SEPARATOR.substr($this->_md5_key, 0, 2);
$ever .= DIRECTORY_SEPARATOR.substr($this->_md5_key, 2, 2);
$this->_file = TL_FSO::getMultDir(_ROOT_DIR_, $ever).$this->_md5_key;
$this->_mem = TL_Mem::getInstance();
}
public function get()
{
$this->_md5_val = $this->_mem->get($this->_md5_key);
$res = TL_FSO::getFileContent($this->_file);
if (!$this->_mem->verify() || $this->_md5_val == md5($res)) {
return unserialize($res);;
}
//error_log('get from cache');
return null;
}
public function set($val)
{
$val = serialize($val);
$this->_mem->set($this->_md5_key, md5($val));
return TL_FSO::createFile($this->_file, $val);
}
public function delete()
{
$this->_mem->delete($this->_md5_key);
TL_FSO::deleteFile($this->_file);
}
public function getVal($key)
{
return $this->get();
}
public function setVal($key, $val)
{
return $this->set($val);
}
}