A good introduction to PHP cache classes and PHP cache functions and their use_PHP tutorial

WBOY
Release: 2016-07-13 10:32:29
Original
813 people have browsed it

Caching is widely used in actual use, which can reduce access to the server database and improve operating speed. At present, many CMS content management systems frequently use caching mechanisms to improve the efficiency of system operation. Below is a well-written cache class. You can refer to the cache mechanism and writing method.

cache.php code is as follows:

<?  
/* 
用户需要事先定义的常量: 
_CachePath_        模板缓存路径 
_CacheEnable_        自动缓存机制是否开启,未定义或为空,表示关闭自动缓存机制 
_ReCacheTime_        自动重新缓存间隔时间,单位为秒,未定义或为空,表示关闭自动重新缓存 
*/  
  
class cache 
{
	var $cachefile;  
	var $cachefilevar;  
  
	function cache() 
	{  
        //生成当前页的Cache组文件名 $this->cachefilevar 及文件名 $this->cachefile  
        //动态页的参数不同对应的Cache文件也不同,但是每一个动态页的所有Cache文件都有相同的文件名,只是扩展名不同  
        $s=array(".","/");$r=array("_","");  
        $this->cachefilevar=str_replace($s,$r,$_SERVER["SCRIPT_NAME"])."_".$_GET[_ActionVar_];  
        $this->cachefile=$this->cachefilevar.".".md5($_SERVER["REQUEST_URI"]);  
	}  
  
	//删除当前页/模块的缓存  
	function delete() 
	{  
        //删除当前页的缓存  
        $d = dir(_CachePath_);  
        $strlen=strlen($this->cachefilevar);  
        //返回当前页的所有Cache文件组  
        while (false !== ($entry = $d->read())) 
		{  
       		if (substr($entry,0,$strlen)==$this->cachefilevar) 
			{  
           		if (!unlink(_CachePath_."/".$entry)) {echo "Cache目录无法写入";exit;}  
         	}  
     	}  
	}  
  
	//判断是否已Cache过,以及是否需要Cache  
	function check() 
	{  
        //如果设置了缓存更新间隔时间 _ReCacheTime_  
        if (_ReCacheTime_+0>0)
		{  
       		//返回当前页Cache的最后更新时间  
         	$var=@file(_CachePath_."/".$this->cachefilevar);$var=$var[0];  
         	//如果更新时间超出更新间隔时间则删除Cache文件  
       		if (time()-$var>_ReCacheTime_) 
			{  
           		$this->delete();$ischage=true;  
         	}  
  		}  
        //返回当前页的Cache  
        $file=_CachePath_."/".$this->cachefile;  
        //判断当前页Cache是否存在 且 Cache功能是否开启  
        return (file_exists($file) and _CacheEnable_ and !$ischange);  
	}  
  
	//读取Cache  
	function read() 
	{  
    	//返回当前页的Cache  
        $file=_CachePath_."/".$this->cachefile;  
        //读取Cache文件的内容  
        if (_CacheEnable_) return readfile($file);  
        else return false;  
	}  
  
	//生成Cache  
	function write($output) 
	{  
        //返回当前页的Cache  
        $file=_CachePath_."/".$this->cachefile;  
        //如果Cache功能开启  
        if (_CacheEnable_) 
		{  
          	//把输出的内容写入Cache文件  
       		$fp=@fopen($file,'w');  
           	if (!@fputs($fp,$output)) {echo "模板Cache写入失败";exit;}  
           	@fclose($fp);  
           	//如果设置了缓存更新间隔时间 _ReCacheTime_  
          	if (_ReCacheTime_+0>0) 
			{  
               	//更新当前页Cache的最后更新时间  
             	$file=_CachePath_."/".$this->cachefilevar;  
               	$fp=@fopen($file,'w');  
              	if (!@fwrite($fp,time())) {echo "Cache目录无法写入";exit;}  
             	@fclose($fp);  
          	}  
   		}  
	}  
}  
?>
Copy after login


Usage of class:

<?php  
	define("_CachePath_","./cache/");  
	define("_CacheEnable_","1");  
	define("_ReCacheTime_","43200");  
	include('cache.php');  
	$cache=new cache();  
	if ($cache->check()) 
	{  
		$template=$cache->read();  
	}
	else 
	{  
 		ob_start();  
     	ob_implicit_flush(0);  
?>  
	页面内容。。。。  
<?php  
		$template = ob_get_contents();  
		$cache->write($template);  
	}  
?>  
Copy after login


Introduction to PHP’s cache related functions

Some information, such as information that is often constant but can still change, is placed in the cache to speed up display. This is very valuable. The so-called cache is generally understood to be some shared information stored on the server side. It lives and dies with the server. When we save the cache, we can specify the judgment of the next update time. For example, if we want to update every 5 minutes, we can record the last update time and compare it with the current time. If it is greater than 5 minutes, Read the database and update it, otherwise read the cached data directly. Of course, the cache needs to be activated by the client user and only needs to be activated once.

ob_start() function

ob_start() function: Open the output buffer.

Function format void ob_start(void)

Note: When the buffer is activated, all non-file header information from the PHP program will not be sent, but will be saved in the internal buffer. In order to output the contents of the buffer, you can use ob_end_flush() or flush() to output the contents of the buffer.

flush() function

Function format: flush()

Description: This function is frequently used and is very efficient.

string ob_get_contents() function

ob_get_contents: Returns the contents of the internal buffer.

Function format: string ob_get_contents(void)

Description: This function will return the contents of the current buffer. If the output buffer is not activated, it will return FALSE.

ob_get_length() function

ob_get_length: Returns the length of the internal buffer.

Function format: int ob_get_length(void)

Description: This function will return the length in the current buffer; like ob_get_contents, if the output buffer is not activated, it will return FALSE.

ob_end_clean() function

ob_end_clean: Delete the contents of the internal buffer and close the internal buffer.

Function format: void ob_end_clean(void)

Description: This function will not output the contents of the internal buffer but delete it.

ob_end_flush() function

ob_end_flush: Send the contents of the internal buffer to the browser and close the output buffer

Function format: void ob_end_flush(void)

Description: This function sends the contents of the output buffer (if any).

ob_implicit_flush() function

Function format: void ob_implicit_flush ([int flag])

Note: The buffer is turned off by default. After absolute output is turned on, each script output is sent directly to the browser, and there is no need to call flush().

Research on PHP caching technology for static pages

If your website’s MySQL database is slow, you need to pay attention to the website’s cache. Friends who have used WordPress know that it has a plug-in called WP Super Cache, which can store WordPress pages as static pages when they are first generated. When the page is requested again, it saves the time of reading the database. It is this technique that is discussed here.

The first question is how to obtain the content output by PHP. The reason for obtaining the output content is simple, because we can store the output content and give the visitor the pre-saved content when he comes again.

Achieving these goals is just as easy. We only need to call the function ob_start() before the content is output, then call ob_get_contents() after all the content is output to obtain the output content, and then call ob_end_flush() to indicate the end. A simple example is as follows:

<?php ob_start(); ?>

<p>在 PHP 标签之外的输出可以被记录。</p>
<?php echo '<p>我被记录了。</p>' ?>

<?php $cache = ob_get_contents(); ?>
<?php
	/* 在这里添加任何处理 $cache 的代码 */
	echo $cache;
?>

<?php ob_end_flush(); ?>
Copy after login


Program running result:

在 PHP 标签之外的输出可以被记录。
我被记录了。

在 PHP 标签之外的输出可以被记录。
我被记录了。
Copy after login

It can be seen that the $cache variable saves the previous output results. That is to say, we can reduce PHP's result output through cache.

Sometimes we have the habit of not enabling caching for administrators, but enabling caching for visitors. At this time, it is actually relatively simple to implement. We can write two functions cache($id) and end_cache($id) ourselves, which represent the start of cache and the end of cache respectively, and then the code is as follows (three functions are omitted here):

<?php

function is_admin() {
  /* 该函数用于测试当前用户是否是管理员,若是管理员则返回 true. */
}

function show_cache($id) {
  /* 根据 $id 读取并显示缓存内容,若无缓存则返回 false. */
}

function save_cache($id, $content) {
  /* 将标识符为 $id 的缓存,以内容 $content 储存。 */
}

function cache($id) {
  if (is_admin())
    return false;
  if (show_cache($id))
    return false;
  ob_start();
  return true;
}

function end_cache($id) {
  if (is_admin())
    return false;
  save_cache($id, ob_get_contents());
  ob_end_flush();
  return true;
}

?>
Copy after login

有的时候,站点可能会根据需要,建立了专门为移动设备设计的页面。那么,这种情况下我们就应该将 $id 扩展一下。这种扩展有很多种方法,比如添加另一个参数,将移动设备的页面存在不同于桌面设备的文件夹中,而这些页面使用相同的 $id . 另外还有一种做法,就是将原来的 $id 与移动设备的 User-agent 糅合在一起,md5() 一下就可以了。我偏向于前面那种做法。当然肯定还有其它类似的做法,总之中心思想就是把缓存的标记 ($id) 设置成不一样的东西,并且当用户回来后还能区别得出它们,就可以了。

还有的时候,一个网站有多种用户角色,可能要给相应的用户相应的缓存。当然,只需遵循上面的原则。

ob_start() 和 ob_end_flush() 是递归处理的。也就是说,可以在调用 ob_end_flush() 之前,调用若干次 ob_start() . 例如:

有的时候,站点可能会根据需要,建立了专门为移动设备设计的页面。那么,这种情况下我们就应该将 $id 扩展一下。这种扩展有很多种方法,比如添加另一个参数,将移动设备的页面存在不同于桌面设备的文件夹中,而这些页面使用相同的 $id . 另外还有一种做法,就是将原来的 $id 与移动设备的 User-agent 糅合在一起,md5() 一下就可以了。我偏向于前面那种做法。当然肯定还有其它类似的做法,总之中心思想就是把缓存的标记 ($id) 设置成不一样的东西,并且当用户回来后还能区别得出它们,就可以了。

还有的时候,一个网站有多种用户角色,可能要给相应的用户相应的缓存。当然,只需遵循上面的原则。

ob_start() 和 ob_end_flush() 是递归处理的。也就是说,可以在调用 ob_end_flush() 之前,调用若干次 ob_start() . 例如:

<?php
ob_start();
echo 'content1'.'<br />';

ob_start();
echo 'content2'.'<br />';

$output1 = ob_get_contents(); 
echo $output1.'<br />';
ob_end_flush();
$output2 = ob_get_contents(); 
echo $output2.'<br />';
ob_end_flush();
?>
Copy after login

程序运行结果:

content1
content2
content2

content1
content2
content2
Copy after login


www.bkjia.comtruehttp://www.bkjia.com/PHPjc/755771.htmlTechArticle缓存在实际使用当中应用很广泛,可以减轻对服务器数据库的访问,提高运行速度。目前很多CMS内容管理系统中频繁使用缓存机制来提高系...
Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template