<?php
/*
這是一個簡易的快取物件cache
作者:二林網管 村仔 2009.09.07
公共GPL版權
用法:
$Cache=new myCache();
$Cache->dir='/home/edu/html';
$Cache->type='text';//預設為陣列,非陣列才寫
$Cache->save('名稱',$data);
$Cache->get('名稱');//取資料
*/
class myCache{
private $ext='.cache';//附檔名
var $dir;//快取檔案路徑
public $limit=300;//5分*60秒 多少時間內的線上人數,可由外部指定
public $type='array';//或text
//建構函式,起始
public function __construct() {
}
//存入快取
public function save($id,$data) {
$fn=$this->dir.$id.$this->ext;
//先判斷檔案存在否
if (file_exists($fn)) {$this->del($id);}//存在時如何處理
if ($this->makeFile($fn)){
if ($this->type=='array'){$str=serialize($data);}else{$str=$data;}
$fp=fopen($fn,"w");
fwrite ($fp,$str);
fclose($fp);
}
}
//取出快取
public function get($id) {
$fn=$this->dir.$id.$this->ext;
//先判斷檔案存在否
if (!file_exists($fn)) {return false;}//存在時如何處理
$str = @file_get_contents($fn);
if (!empty($str)){
if ($this->type=='array'){$data=unserialize($str);}else{$data=$str;}
//$data=unserialize($str);
return $data;
}
}
//刪除快取
public function del($id) {
$fn=$this->dir.$id.$this->ext;
if (file_exists($fn)) unlink($fn);//存在時如何處理
}
public function makeFile($file) {
$fp=fopen($file,"a");
if ($fp){fclose($fp);return true;}
else {return false;}
}
}
//end class
程式CODE
2015年7月28日 星期二
cache語法!搭配序列化及反序列
訂閱:
張貼留言 (Atom)
沒有留言:
張貼留言