php 自带缓存,封装ThinkPhP自带的缓存机制
namespace Home\Controller;
use Think\Controller;
use Think\Think;
/**
* @param string $cache_folder 緩文件夾
* @param int $cache_create_time 文件緩存時間
* @example $cache->read_cache() 讀取緩存并輸出
* @example $cache->create_cache() 創建緩存文件(放在文件未尾)
* @example $cache->list_file() 返回所有緩存文件列表
* @example $cache->del_file() 刪除所有緩存文件
*/
class CacheController extends Controller {
private $cache_folder = null; //cacher文件夾
private $wroot_dir = null; //站點目錄
private $cacher_create_time = null; //cacher文件的建立時間
private $id = null;
public function chushi($cache_foldername,$id) {
ob_start();
$this->wroot_dir = $_SERVER['DOCUMENT_ROOT'];
$this->cache_folder = $cache_foldername;
$this->cacher_create_time=C('CON_TIME');
$this->id=$id;
}
public function read_cache() {
try {
if (self::create_folder($this->cache_folder)) {
self::get_cache(); //輸出緩存文件信息
} else {
echo "緩存文件夾創建失敗!";
return false;
}
} catch (Exception $e) {
echo $e;
return false;
}
}
//測試緩存文件夾是否存在
private function exist_folder($foler) {
if (file_exists($this->wroot_dir . "/" . $foler)) {
return true;
} else {
return false;
}
}
//建立一個新的文件夾
private function create_folder($foler) {
if (!self::exist_folder($foler)) {
try {
mkdir($this->wroot_dir . "/" . $foler, 0777);
chmod($this->wroot_dir . "/" . $foler, 0777);
return true;
} catch (Exception $e) {
self::get_cache(); //輸出緩存
return false;
}
return false;
} else {
return true;
}
}
//讀取緩存文件
private function get_cache() {
$file_name = self::get_filename();
if (file_exists($file_name) && ((filemtime($file_name) + $this->cacher_create_time) > time())) {
$content = file_get_contents($file_name);
if ($content) {
echo $content;
ob_end_flush();
exit;
} else {
echo "文件讀取失敗";
exit;
}
}
}
//返回文件的名字
private function get_filename() {
$filename = $file_name = $this->wroot_dir . '/' . $this->cache_folder . '/' . $this->id . ".html";
return $filename;
}
//建立緩存文件
public function create_cache() {
$filename = self::get_filename();
if ($filename != "") {
try {
file_put_contents($filename, ob_get_contents());
return true;
} catch (Exception $e) {
echo "寫緩存失敗:" . $e;
exit();
}
return true;
}
}
// 取得緩存中的所有文件
public function list_file() {
$path = $this->cache_folder;
if ($handle = opendir($path)) {
while (false !== ($file = readdir($handle))) {
if ($file != "." && $file != "..") {
$path1 = $path . "/" . $file;
if (file_exists($path1)) {
$result[] = $file;
}
}
}
closedir($handle);
}
return $result;
}
//刪除緩存中的所有文件
public function del_file() {
$path = $this->cache_folder;
if ($handle = opendir($path)) {
while (false !== ($file = readdir($handle))) {
if ($file != "." && $file != "..") {
$path1 = $path . "/" . $file;
if (file_exists($path1)) {
unlink($path1);
}
}
}
closedir($handle);
}
return true;
}
}
總結
以上是生活随笔為你收集整理的php 自带缓存,封装ThinkPhP自带的缓存机制的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 优先级调度算法和高响应比优先调度算法
- 下一篇: exception日志 php_PHP