[译]通过php缓存你的页面

文章分类:PHP  查看次数:409 + 91

原文地址:click here

使用缓存技术可以缓解服务器的负担

简介
这篇文章将简要介绍一下什么是缓存系统,以及如何和为什么要使用它。

目前,大多数的网站都是基于数据库的动态页面。也就是说你的页面相当于一个从数据库系统(比如MySQL)获得数据的应用程序,解析数据,然后呈现给用户。大多数的数据并不是经常更新,我们使用数据库的原因是可以非常方便的更新数据和内容。

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

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

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

代码进行时

下面是一段代码示例

<?
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。

修正不足

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

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

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

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

评论

发表评论