PHP缓存技术

web开发中巧妙的使用缓存技术,不尽减少了服务器压力,而且还会增加浏览速度,下面主要讲解在php中如何使用缓存技术来缓存页面。
    大多数的网站都是基于数据库的动态页面。也就是说你的页面相当于一个从数据库系统(比如MySQL)获得数据的应用程序,解析数据,然后呈现给用户。大多数的数据并不是经常更新,我们使用数据库的原因是可以非常方便的更新数据和内容。

      大量过多的数据库连接和查询将会导致服务器过载或瘫痪。每查询一次数据库,脚本就链接一次DBMS,然后DBMS将返回查询的结果。这非常浪费时间和资源,如果频率非常高的话,可能会导致数据库出错。

如何搞定这个问题?
有两种方法可以解决这个问题。一个是优化查询,但在本文不讨论这个;另一个最常用的就是使用缓存。

使用缓存技术
下面让我来解释一下。当我们有一个数据更新不是很频繁的动态页面时,我们可以通过'系统'来创建页面,然后留着以后用。也就是说当页面创建完成后,只要没有过期,就不需要再次查询数据库,而只是展示缓存页。当然系统必须要设置一个过期的时间。

下面是一段代码示例

 

<?php
class cache
{
var $cache_dir = './tmp/cache/';//This is the directory where the cache files will be stored;
var $cache_time = 1000;//How much time will keep the cache files in seconds.

var $caching = false;
var $file = '';

function cache()
{
//Constructor of the class
$this->file = $this->cache_dir . urlencode( $_SERVER['REQUEST_URI'] );
if ( file_exists ( $this->file ) && ( fileatime ( $this->file ) + $this->cache_time ) > time() )
{
//Grab the cache:
$handle = fopen( $this->file , "r");
do {
$data = fread($handle, 8192);
if (strlen($data) == 0) {
break;
}
echo $data;
} while (true);
fclose($handle);
exit();
}
else
{
//create cache :
$this->caching = true;
ob_start();
}
}

function close()
{
//You should have this at the end of each page
if ( $this->caching )
{
//You were caching the contents so display them, and write the cache file
$data = ob_get_clean();
echo $data;
$fp = fopen( $this->file , 'w' );
fwrite ( $fp , $data );
fclose ( $fp );
}
}
}

//Example :
$ch = new cache();
echo date("D M j G:i:s T Y");
$ch->close();
?>

代码功能介绍如下:

function cache()
这是这个类的构造函数,这个函数的功能就是检测是否已经存在缓存页,或者缓存页是否已经过期并创建之。下面就是它如何做到的:


$this->file = $this->cache_dir . urlencode( $_SERVER['REQUEST_URI'] );


这段代码就是创建一个目标文件,这个目标文件就像这样:/path/to/cache/dir/request_uri


if ( file_exists ( $this->file ) && ( fileatime ( $this->file ) + $this->cache_time ) > time() )

这段代码检测是否存在缓存页,或者需要重建缓存页因为可能已经过期。如果缓存页还在保质期,那么就显示缓存页然后退出。我下面解释为什么要退出。如果必须重建缓存页,那么下面这段代码将起作用

$this->caching = true;
ob_start();


第一句话指示开始创建缓存页面,第二句话就开始了缓存,缓存的数据会在调用close()函数时使用。


function close()

这个函数必须在脚本末尾被调用,它将完成最后的工作。

下面来解释一下这个函数是怎么工作的

$data = ob_get_clean();

这里我们得到了调用这个函数之前的所有缓存内容,同时删除缓存,并将其值赋予$data。

这是一个非常简单的类,目的是了解缓存并更好地运用到自己的网站中。如果要使用这个类,则必须以下面这种形式

<?php
$a = new cache();
....
....
....
$a->close();
?>

如果在$a->close()之后还有代码,那么这些代码将无效。因为在cache()函数里有exit。一个比较好的解决方法是从cache函数中移去exit函数,然后像下面这样使用

<?php
$a = new cache();
if ( $a->caching )
{
....
....
....
}
$a->close();
?>

熟练的使用缓存技术,是你工作效率事半功倍!

本文来自[<a href='http://www.houxd.com' target='_blank'>后现代网络资源门户</a>]! 详细出处参考:http://www.lindsoft.net/html/net_tech/php/rmCXyKWZtKK0sC2w.htm

你可能感兴趣的:(数据库,PHP,cache,function,File,caching)