PHP文件緩存類示例分享
更新時間:2015年01月30日 16:34:58 投稿:hebedich
這里給大家分享一個php文件緩存類,十分實用,給需要的小伙伴們參考下。
復(fù)制代碼 代碼如下:
<?php
/**
* @desc 文件緩存
*/
class Cache{
const C_FILE = '/Runtime/';
private $dir = '';
const EXT = '.tpl';
private $filename = '';
public function __construct($dir = ''){
$this->dir = $dir;
}
/**
* @desc 設(shè)置文件緩存
* @param string $key 文件名
* @param unkonw $data 緩存數(shù)據(jù)
* @param int $expire 過期時間
*/
public function set($key,$data,$expire = 0){
$this->filename = dirname(__FILE__).self::C_FILE.$this->dir.$key.self::EXT;
if(file_exists($this->filename)){
$res = $this->get($key);
if(md5($res) == md5(json_encode($data) ) ){
return true;
}
}
if(!is_dir(dirname($this->filename))){
mkdir(dirname($this->filename),0777);
}
$source = fopen($this->filename,'w+');
fwrite($source,json_encode($data));
fclose($source);
}
/**
* @desc 獲取文件
* @param string $key 文件名
*/
public function get($key){
//$filename = dirname(__FILE__).self::C_FILE.$this->dir.$key.self::EXT;
if(!file_exists($this->filename)){
return '緩存文件已經(jīng)不存在';
}else{
$res = file_get_contents($this->filename);
}
return $res;
}
/**
* @desc 刪除文件
* @param string $key 文件名
*/
public function del($key){
unlink($this->filename);
}
}
$data = array('name'=>'song','age'=>20,'sex'=>'man','favority'=>array('apple','banana'));
$cache = new Cache();
$cache->set('cache',$data);
//$cache->get('cache');
//$cache->del('cache');
相關(guān)文章
利用php-cli和任務(wù)計劃實現(xiàn)刷新token功能的方法
下面小編就為大家?guī)硪黄胮hp-cli和任務(wù)計劃實現(xiàn)刷新token功能的方法。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-05-05
PHP內(nèi)核學(xué)習(xí)教程之php opcode內(nèi)核實現(xiàn)
opcode是計算機指令中的一部分,用于指定要執(zhí)行的操作, 指令的格式和規(guī)范由處理器的指令規(guī)范指定,通過本文給大家介紹PHP內(nèi)核學(xué)習(xí)教程之php opcode內(nèi)核實現(xiàn),感興趣的朋友一起學(xué)習(xí)吧2016-01-01
ThinkPHP關(guān)于session的操作方法匯總
這篇文章主要介紹了ThinkPHP關(guān)于session的操作方法,有助于讀者加深對ThinkPHP操作session的認(rèn)識,需要的朋友可以參考下2014-07-07

