ECMALL源码阅读八:数据缓存

ECMALL提供了2种数据缓存,有名的memcached与自已实现的PhpCacheServer(includes\libraries\cache.lib.php)。 默认是PhpCacheServer。这些实现过程都非常简单。但是过程有点巧妙。PhpCacheServer把缓存数据序列化成字符串 保存在PHP文件中。当需要时,只需要include缓存文件,就可以读取出来。如果数据量不是很大,其实PhpCacheServer就已经足够满足需求。 这种小而美的工具让人兴奋。

缓存保存 (includes\librariescache.lib.php)

<?php
function set($key, $value, $ttl = 0)
{
	if (!$key)
	{
		return false;
	}
	/*根据key生成文件名*/
	$cache_file = $this->_get_cache_path($key);
	/*生成缓存保存时间,有效期*/
	$cache_data = "<?php\r\n/**\r\n *  
	@Created By ECMall PhpCacheServer\r\n *  @Time:" 
	. date('Y-m-d H:i:s') . "\r\n */";
	$cache_data .= $this->_get_expire_condition(intval($ttl));
	/*把数组转换成字符串形式*/
	$cache_data .= "\r\nreturn " . var_export($value, true) .  ";\r\n";
	$cache_data .= "\r\n?>";
    /*保存成PHP文件*/
	return file_put_contents($cache_file, $cache_data, LOCK_EX);
}
?>

缓存读取 (includes\librariescache.lib.php)

<?php
/*引用传递,避免浪费内存*/
function &get($key)
{
	/*根据key获取文件路径*/
	$cache_file = $this->_get_cache_path($key);
	if (!is_file($cache_file))
	{
		return false;
	}
	/*包含文件*/
	$data = include($cache_file);
    /*返回数据*/
	return $data;
}
?>