Home  >  Article  >  Backend Development  >  A PHP cache class, with three examples of Demo code_PHP tutorial

A PHP cache class, with three examples of Demo code_PHP tutorial

WBOY
WBOYOriginal
2016-07-21 14:53:50863browse

一个PHP缓存类,附三个实例Demo代码,本文由烈火小编收集于网络,首先我们看到的是cache.inc.php文件,请大家将以下代码保存为: cache.inc.php。

Copy to ClipboardLiehuo.Net Codes引用的内容:[www.bkjia.com]
class Cache {
/**
* $dir : 缓存文件存放目录
* $lifetime : 缓存文件有效期,单位为秒
* $cacheid : 缓存文件路径,包含文件名
* $ext : 缓存文件扩展名(可以不用),这里使用是为了查看文件方便
*/
private $dir;
private $lifetime;
private $cacheid;
private $ext;
/**
* 析构函数,检查缓存目录是否有效,默认赋值
*/
function __construct($dir='',$lifetime=1800) {
if ($this->dir_isvalid($dir)) {
$this->dir = $dir;
$this->lifetime = $lifetime;
$this->ext = '.Php';
$this->cacheid = $this->getcacheid();
}
}
/**
* 检查缓存是否有效
*/
private function isvalid() {
if (!file_exists($this->cacheid)) return false;
if (!(@$mtime = filemtime($this->cacheid))) return false;
if (mktime() - $mtime > $this->lifetime) return false;
return true;
}
/**
* 写入缓存
* $mode == 0 , 以浏览器缓存的方式取得页面内容
* $mode == 1 , 以直接赋值(通过$content参数接收)的方式取得页面内容
* $mode == 2 , 以本地读取(fopen ile_get_contents)的方式取得页面内容(似乎这种方式没什么必要)
*/
public function write($mode=0,$content='') {
switch ($mode) {
case 0:
$content = ob_get_contents();
break;
default:
break;
}
ob_end_flush();
try {
file_put_contents($this->cacheid,$content);
}
catch (Exception $e) {
$this->error('写入缓存失败!请检查目录权限!');
}
}
/**
* 加载缓存
* exit() 载入缓存后终止原页面程序的执行,缓存无效则运行原页面程序生成缓存
* ob_start() 开启浏览器缓存用于在页面结尾处取得页面内容
*/
public function load() {
if ($this->isvalid()) {
echo "This is Cache. ";
//以下两种方式,哪种方式好?????
require_once($this->cacheid);
//echo file_get_contents($this->cacheid);
exit();
}
else {
ob_start();
}
}
/**
* 清除缓存
*/
public function clean() {
try {
unlink($this->cacheid);
}
catch (Exception $e) {
$this->error('清除缓存文件失败!请检查目录权限!');
}
}
/**
* 取得缓存文件路径
*/
private function getcacheid() {
return $this->dir.md5($this->geturl()).$this->ext;
}
/**
* 检查目录是否存在或是否可创建
*/
private function dir_isvalid($dir) {
if (is_dir($dir)) return true;
try {
mkdir($dir,0777);
}
catch (Exception $e) {
$this->error('所设定缓存目录不存在并且创建失败!请检查目录权限!');
return false;
}
return true;
}
/**
* 取得当前页面完整url
*/
private function geturl() {
$url = '';
if (isset($_SERVER['REQUEST_URI'])) {
$url = $_SERVER['REQUEST_URI'];
}
else {
$url = $_SERVER['Php_SELF'];
$url .= empty($_SERVER['QUERY_STRING'])?'':'?'.$_SERVER['QUERY_STRING'];
}
return $url;
}
/**
* 输出错误信息
*/
private function error($str) {
echo '
'.$str.'
';
}
}
?>

The following are three example DEMOs. Please save the following codes as demo.php or other file names. Pay attention to the file path and make sure there is no mistake.

/*
* Can be freely reproduced and used, please keep the copyright information, thank you for using it!
* Class Name: Cache (For Php5)
* Version: 1.0
* Description: Dynamic cache class, used to control the page to automatically generate cache, call cache, update cache, and delete cache.
* Author: jiangjun8528@163.com, Junin
* Author Page: http://blog .csdn.Net/sdts/
* Source code from: Agni Download http://www.bkjia.com/down
* Last Modify: 2007-8-22
* Remark:
1. This version is the Php5 version. I have not written the Php4 version yet. If necessary, please refer to it and modify it yourself (it’s easier, don’t be so lazy, haha!).
2. This version is encoded in utf-8, if the website uses Please convert other codes by yourself. For Windows systems, use Notepad to open and save as, and select the corresponding code (generally ANSI). For Linux, please use the corresponding editing software or the iconv command line.
3. Don’t worry about the above paragraph if you copy and paste it. 2 items.
* Some thoughts about caching:
* The fundamental difference between dynamic caching and static caching is that it is automatic. The process of user accessing the page is the process of generating cache, browsing cache and updating cache. No manual work is required. Operational intervention.
* Static caching refers to generating static pages. Related operations are generally completed in the background of the website and require manual operation (that is, manual generation).
*/

/*
* Usage examples
--------------------------------Demo1----- -------------------------------------

require_once('cache.inc .php');
$cachedir = './Cache/'; //Set the cache directory
$cache = new Cache($cachedir,10); //Omit the parameters and use the default settings, $ cache = new Cache($cachedir);
if ($_GET['cacheact'] != 'rewrite') //Here is a trick, update the cache through xx.Php?cacheact=rewrite, and so on, You can also set some other operations
$cache->load(); //Load the cache. If the cache is valid, the following page code will not be executed
//The page code starts
echo date('H:i :s jS F');
//End of page code
$cache->write(); //First run or cache expiration, generate cache

------- --------------------------------Demo2----------------------------- -----------------------

require_once('cache.inc.php');
$cachedir = './Cache /'; //Set the cache directory
$cache = new Cache($cachedir,10); //Omit the parameters and use the default settings, $cache = new Cache($cachedir);
if ($ _GET['cacheact'] != 'rewrite') //Here is a trick, update the cache through xx.Php?cacheact=rewrite, and so on, you can also set some other operations
$cache-> load(); //Load the cache. If the cache is valid, the following page code will not be executed
//The page code starts
$content = date('H:i:s jS F');
echo $content ;
//End of page code
$cache->write(1,$content); //First run or cache expiration, generate cache

--------- ----------------------------Demo3---------------------- ---------------------

require_once('cache.inc.php');
define('CACHEENABLE',true);

if (CACHEENABLE) {
$cachedir = './Cache/'; //Set the cache directory
$cache = new Cache($cachedir,10); //Omit the parameters. Adopt the default settings, $cache = new Cache($cachedir);
if ($_GET['cacheact'] != 'rewrite') //This is a trick, update through xx.Php?cacheact=rewrite Cache, and so on, you can also set some other operations
$cache->load(); //Load cache, if the cache is valid, the following page code will not be executed
}
//Start of page code
$content = date('H:i:s jS F');
echo $content;
//End of page code
if (CACHEENABLE)
$cache->write (1,$content); //First run or cache expiration, generate cache
*/
?>

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/364712.htmlTechArticleA PHP cache class with three example Demo codes. This article was collected from the Internet by the editor Agni. First, let’s look at What you have arrived is the cache.inc.php file. Please save the following code as: cache.inc...
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn