最近一个项目中涉及到用户没有写完的文章保存到草稿箱,在网上搜索说可以放到客户端的cookie里面,但是回数据量大的话,这样就行不通了;
另一种方法是放到数据库中,为这个草稿定制一张草稿数据表,这样就直接走数据库,但是如果这条草稿数据不正式发布的话,或者需要删除,又需要去到数据库中进行一系列的操作,这样执行起来体验度会降低。
最后选择了文件缓存,操作简单,访问数据快,容量也不需要担心。
把用户发布的数据以序列化的数组形式放到文件中,读取写入都比较方便
下面是在网上搜的一篇简单的文件缓存类:
<?php
/**
* 文件缓存.
* User: Pengfan
* Time: 13:50
*/
class Inc_FileCache
{
//默认缓存时间
private $cacheTime = 3600;
//缓存绝对路径
private $cacheDir = './cache';
//是否对键进行加密
private $md5 = true;
//设置文件后缀
private $suffix = '.php';
/**
* 构造函数
*/
public function __construct($config)
{
if(is_array($config)){
foreach ($config as $key => $val){
$this->$key = $val;
}
}
}
/**
* 设置缓存
* @param string $key 缓存key
* @param string $val 文件内容
* @param string $leftTime 缓存时间
*/
public function setCache($key,$val,$leftTime = null)
{
$key = $this->md5 ? md5($key) : $key;
$leftTime = $leftTime ? $leftTime : $this->cacheTime;
//是否存在文件夹并创建
!file_exists($this->cacheDir) && mkdir($this->cacheDir,0777);
$file = $this->cacheDir . '/' . $key . $this->suffix;
$val = serialize($val);
//写入文件
@file_put_contents($file,$val) or $this->error(__LINE__,'value enter file fail');
//设置文件权限
@chmod($file,0777) or $this->error(__LINE__,'set file power fail');
//设置过期时间
@touch($file,time() + $leftTime) or $this->error(__LINE__,'update file time fail');
}
/**
* 获取文件缓存
* @param string $key 文件缓存key
* @return array
*/
public function getCache($key)
{
$this->clear();
if($this->_isset($key))
{
$key_md5 = $this->md5 ? md5($key) : $key;
$file = $this->cacheDir . '/' . $key_md5 .$this->suffix;
$val = file_get_contents($file);
return unserialize($val);
}
return null;
}
/**
* 文件是否有效
* @param string $key 文件key
* @return boolean
*/
public function _isset($key)
{
$key = $this->md5 ? md5($key) : $key;
$file = $this->cacheDir . '/' . $key . $this->suffix;
if(file_exists($file))
{
if(@fileatime($file) >= time())
{
return true;
}
else
{
@unlink($file);
return false;
}
}
return false;
}
/**
* 删除文件
* @param string $key 文件key
*/
public function delCache($key)
{
$key = $this->md5 ? md5($key) : $key;
$file = $this->cacheDir . '/' . $key . $this->suffix;
if(file_exists($file)){
@unlink($file);
}else{
$this->error(__LINE__,'file not find');
}
}
/**
* 清除过期文件
*/
public function clear()
{
//列出文件夹中的文件以及文件夹
$files = scandir($this->cacheDir);
foreach ($files as $val)
{
if(@fileatime($this->cacheDir . '/' . $val) < time()){
//删除文件
@unlink($this->cacheDir . '/' . $val);
}
}
}
/**
* 删除缓存
*/
public function clear_all()
{
$files = scandir($this->cacheDir);
foreach ($files as $val)
{
@unlink($this->cacheDir . '/' .$val);
}
}
/**
* 输错错误
*/
private function error($line,$msg)
{
throw new \Exception("file error:" . __FILE__ . "/n error line: {$line} /n error msg:{$msg}");
}
}