缓存的工作原理
缓存的工作原理其实并不复杂。它的核心思想是:首先,我们将需要显示的内容存储在一个文本文件(即缓存文件)之中。然后,如果有用户请求某个页面的内容,我们首先检查此页对应的缓存(即那个文本文件)是否存在——如果存在且为最新的缓存文件,那么直接将这个文本文件中的内容输出到客户端供用户查看;如果此页对应的缓存文件不存在或缓存生成的时间不符合要求(太旧),那么直接执行一次此页对应的PHP文件,并将显示内容存储在缓存文件中。重复上述流程。这样一来,虽然增加了PHP代码,但我们最大程度的节省了PHP链接到数据库教程再提取数据的时间。
<?php //导入缓存类 require_once ('cache.class.php'); //创建一个缓存类对象CacheManager $CacheManager = new Cache(); //调用startCache方法,表示开始缓存 $CacheManager->startCache(); //以下区块所有echo内容都将作为缓存写入缓存文件中 echo "Start Cache example at: " . date('H:i:s') . "<br/>"; sleep(2); echo "End Cache example at: " . date('H:i:s') . "<br/>"; echo "<br/><a href='clear.php'>Clean the cache</a><br/>"; //以上区块所有echo内容都将作为缓存写入缓存文件中 $CacheManager->endCache(); //cache.class.php代码 class Cache { var $status = true; // 值为True表示开启缓存;值False表示关闭缓存功能。 var $cacheDir = 'cache/'; //存放缓存文件的默认目录 var $cacheFile = ''; //缓存文件的真实文件名 var $timeOut = 1000; // 内容被重复使用的最长时限 var $startTime = 0; // 程序执行的开始时间 var $caching = true; // 是否需要对内容进行缓存;值为False表示直接读取缓存文件内容 function getMicroTime() { list($usec, $sec) = explode(" ", microtime()); return ((float)$usec + (float)$sec); } function startCache() { $this->startTime = $this->getMicroTime(); ob_start(); if ($this->status) { $this->cacheFile = $this->cacheDir . urlencode($_SERVER['REQUEST_URI']); if ((file_exists($this->cacheFile)) && ((fileatime($this->cacheFile) + $this->timeOut) > time())) { //从缓存文件中读取内容 $handle = fopen($this->cacheFile, "r"); $html = fread($handle, filesize($this->cacheFile)); fclose($handle); // 显示内容 echo $html; // 显示程序执行时间 echo '<p>Total time: ' . round(($this->getMicroTime()) - ($this->startTime) , 4) . '</p>'; //退出程序 exit(); } else { //置缓存标志caching为true $this->caching = true; } } } function endCache() { if ($this->status) { if ($this->caching) { //首先输出页面内容,然后将输出内容保存在缓存文件中 $html = ob_get_clean(); echo $html; $handle = fopen($this->cacheFile, 'w'); fwrite($handle, $html); fclose($handle); //显示页面执行时间 echo '<p>Total time: ' . round(($this->getMicroTime() - $this->startTime) , 4) . '</p>'; } } } function cleanCache() { if ($handle = opendir($this->cacheDir)) { while (false !== ($file = readdir($handle))) { if (is_file($this->cacheDir . $file)) unlink($this->cacheDir . $file); } closedir($handle); } } } // 再一个简单的php 缓存文件实例代码 if ($content = $cache->start($cache_id)) { echo $content; exit(); } require_once 'Cache/Function.php'; $cacheDir = './pear_cache/'; $cache = new Cache_Function('file', array( 'cache_dir' = > $cacheDir )); $arr = array( '东方', '南方', '西方' ); $cache->call('slowFunction', $arr); echo'<BR>'; $arr = array( '东方', '南方', '西方' ); slowFunction($arr); functionslowFunction($arr = null) { echo"一个执行起来很慢的函数 :( <br>"; echo"当前时间是 " . date('M-d-Y H:i:s A', time()) . '<br>'; foreach($arr as $fruit){ echo"太阳此时正在 $fruit <br>"; } }
文章地址:http://www.phprm.com/code/f0f50ce01424b3c6a3ce00c6b68e082f.html
转载随意^^请带上本文地址!