php文件缓存方法总结文件缓存方法总结
主要为大家详细介绍了php文件缓存方法,内容如很详细,感兴趣的小伙伴们可以参考一下
为大家分享很全的php文件缓存,供大家参考,具体内容如下
<?php
class cache
{
private static $_instance = null;
protected $_options = array(
'cache_dir' => "./",
'file_name_prefix' => 'cache',
'mode' => '1', //mode 1 为serialize model 2为保存为可执行文件
);
/**
* 得到本类实例
*
* @return Ambiguous
*/
public static function getInstance()
{
if(self::$_instance === null)
{
self::$_instance = new self();
}
return self::$_instance;
}
/**
* 得到缓存信息
*
* @param string $id
* @return boolean|array
*/
public static function get($id)
{
$instance = self::getInstance();
//缓存文件不存在
if(!$instance->has($id))
{
return false;
}
$file = $instance->_file($id);
$data = $instance->_fileGetContents($file);
if($data['expire'] == 0 || time() < $data['expire'])
{
return $data['contents'];
}
return false;
}
/**
* 设置一个缓存
*
* @param string $id 缓存id
* @param array $data 缓存内容
* @param int $cacheLife 缓存生命 默认为0无限生命
*/
public static function set($id, $data, $cacheLife = 0)
{
$instance = self::getInstance();
$time = time();
$cache = array();
$cache['contents'] = $data;
$cache['expire'] = $cacheLife === 0 ? 0 : $time + $cacheLife;
$cache['mtime'] = $time;
$file = $instance->_file($id);
return $instance->_filePutContents($file, $cache);
}