針對圖片較多的移動端頁面,通過文件緩存減少數據庫查詢壓力。本文提供一個輕量級緩存類,採用序列化數組寫入文件、讀取反序列化的機制,支持緩存過期時間控制與開關配置。
<?php
/**
* 簡易文件緩存類
* 作者:fianl_m@foxmail.com
*/
class Cache {
private $is_cache; // 是否開啟緩存
private $cache_file; // 緩存目錄
private $cache_time; // 緩存有效期(秒)
public function __construct($config) {
$this->is_cache = $config['is_cache'];
$this->cache_file = $config['cache_file'];
$this->cache_time = $config['cache_time'];
}
/** 讀取緩存 */
public function open($name) {
$filename = $this->cache_file . $name;
// 文件存在且未過期且緩存開啟
if ($this->is_cache && file_exists($filename) && (filemtime($filename) + $this->cache_time > time())) {
$content = file_get_contents($filename);
return unserialize($content);
}
return false;
}
/** 寫入緩存 */
public function write($name, $data = array()) {
$filename = $this->cache_file . $name;
$content = serialize($data);
return file_put_contents($filename, $content);
}
}
// 配置
require('cache.class.php');
$config = array(
'is_cache' => 1, // 開啟
'cache_file' => './cache/', // 緩存目錄(需可寫權限)
'cache_time' => 60, // 60 秒過期
);
$cache = new Cache($config);
// 讀取
$filename = 'article_list';
$row = $cache->open($filename);
if ($row === false) {
// 緩存未命中:查詢數據庫
$row = $db->query("SELECT * FROM articles")->fetchAll();
// 寫入緩存
$cache->write($filename, $row);
}
// 使用 $row 渲染頁面...
serialize()/unserialize() 保留數組結構與類型,適合 PHP 內部數據交換。filemtime() + $cache_time > time() 簡單高效,無需額外元數據文件。chmod 755 或 777)。delete()、flush() 方法支持手動失效。json_encode/decode 替代序列化,提升跨語言兼容性與安全性。此類適合中小型項目快速接入文件緩存,大流量或分布式場景請直接使用專業緩存中間件。