php緩存讀寫

下面的一段代碼是,把數據寫入緩存和讀取緩存數據,然後給緩存一個時間,在緩存生存時間內,我們使用緩存的數據,否則更新緩存。



<?php

class File{
private $_dir;
public function __construct(){
//dirname(__FILE__)當前目錄
$this->_dir=dirname(__FILE__);
}
const EXT ='.txt';
public function cacheData($key,$value ='',$cacheTime = 0){
$filename =$this->_dir."/".$key.self::EXT;
echo $filename;
if ($value!==''){ //將value寫入緩存
//如果value是null,那麼把緩存刪掉。
if (is_null($value)){
return @unlink($filename);
}
$dir =dir($filename);
if (!is_dir($dir))
{
mkdir($dir,0777);
}
//處理緩存時間,這裏我們要設置緩存時間的長度,因爲要截取緩存時間用
      $cacheTime =sprintf("%011d",$cacheTime);

//轉換成字符串的形式。
return file_put_contents($filename, $cacheTime.json_encode($value));
}
//獲取緩存
if (is_file($filename)){
return false;
}

$contents = file_get_contents($filename);
$cacheTime = substr($contents, 0,11);
$value = substr($contents, 11);
if ($cacheTime+filemtime($filename) > time()){
//如果緩存時間過期,從數據庫中組織數據,寫入緩存中。
}

return json_decode($value,true);

}
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章