Home >Backend Development >PHP Tutorial >Detailed discussion of caching technology—php_PHP tutorial

Detailed discussion of caching technology—php_PHP tutorial

WBOY
WBOYOriginal
2016-07-21 15:59:29804browse

1. Introduction

PHP, a web design scripting language that has emerged in recent years, has developed rapidly in recent years due to its power and scalability. Compared with traditional ASP websites, PHP has There is an absolute advantage in speed. If you want to transfer 60,000 pieces of data from mssql to php, it takes 40 seconds, and asp takes no less than 2 minutes. However, as the website has more and more data, we are eager to call the data faster, without having to do it every time. All are removed from the database. We can remove them from other places, such as a file or a certain memory address. This is PHP’s caching technology, which is Cache technology.

2. In-depth analysis

Generally speaking, the purpose of caching is to put data in one place to make access faster. There is no doubt that memory is the fastest, but can hundreds of M of data be stored in it? This is unrealistic, of course. , sometimes it is temporarily placed in the server cache. For example, if the ob_start() cache page is turned on, the page content will be cached in the memory before sending the file header. Until the page output is automatically cleared, or wait for the return of ob_get_contents, or be displayed by ob_end_clean Clearance, which can be well utilized in the generation of static pages and can be well reflected in templates, is a way, but it is temporary and not a good way to solve our problem.

In addition, there is an object application in asp, which can save public parameters. This is also a bit of caching, but in PHP, I have not seen developers produce such objects so far. Indeed, it is not necessary. asp.net The page caching technology uses viewstate, and cache is file association (not necessarily accurate). When the file is modified, the cache is updated. If the file is not modified and does not time out (Note 1), the cache is read and the result is returned, which is For this idea, take a look at this source code:


PHP:[Copy to clipboard]
class cache{
/*
Class Name: cache
Description: control to cache data,$cache_out_time is a array to save cache date time out.
Version: 1.0
Author: old farmer cjjer
Last modify:2006-2-26
Author URL : http://www.cjjer.com
*/
private $cache_dir;
private $expireTime=180;//The cache time is 60 seconds
function __construct($cache_dirname){
if(!@is_dir($cache_dirname)){
if(!@mkdir($cache_dirname,0777)){
$this->warn('The cache file does not exist and cannot be created, it needs to be done manually Create.');
return false;
}
}
$this->cache_dir = $cache_dirname;
}
function __destruct(){
echo 'Cache class bye.';
}

function get_url() {
if (!isset($_SERVER['REQUEST_URI'])) {
$url = $_SERVER['REQUEST_URI' | _SERVER[ 'QUERY_STRING'] : '';
                                                                                                                                                                                                 font color='red'>An error occurred:

".$errorstring."
";
}

function cache_page ($pageurl,$pagedata){
if(!$fso=fopen($pageurl,'w')){
$this->warns('Unable to open cached file.');//trigger_error
return false;
}
if(!flock($fso,LOCK_EX)){//LOCK_NB, exclusive lock
$this->warns('Unable to lock cache file.' );//trigger_error
return false;
}
if(!fwrite($fso,$pagedata)){//Write byte stream, serialize writes other formats
$this- >warns('Unable to write to cache file.');//trigger_error
return false;
}
flock($fso,LOCK_UN);//Release lock
fclose($fso) ;
return true;
}

function display_cache($cacheFile){
if(!file_exists($cacheFile)){
$this->warn('Cannot read Get the cache file.');//trigger_error
return false;
      }
   echo '读取缓存文件:'.$cacheFile;
//return unserialize(file_get_contents($cacheFile));
        $fso = fopen($cacheFile, 'r');
        $data = fread($fso, filesize($cacheFile));
        fclose($fso);
 return $data;
}

function readData($cacheFile='default_cache.txt'){
 $cacheFile = $this->cache_dir."/".$cacheFile;
 if(file_exists($cacheFile)&&filemtime($cacheFile)>(time()-$this->expireTime)){
  $data=$this->display_cache($cacheFile);
  }else{
   $data="from here wo can get it from mysql database,update time is ".date('l dS of F Y h:i:s A').",过期时间是:".date('l dS of F Y h:i:s A',time()+$this->expireTime)."----------";
   $this->cache_page($cacheFile,$data);
 }
  return $data;
}


}
?> 


下面我打断这个代码逐行解释.

三、程序透析

这个缓存类(类没什么好怕的.请继续看)名称是cache,有2个属性:


CODE:[Copy to clipboard]private $cache_dir;
private $expireTime=180;
$cache_dir是缓存文件所放的相对网站目录的父目录, $expireTime(注释一)是我们缓存的数据过期的时间,主要是这个思路:
当数据或者文件被加载的时候,先判断缓存文件存在不,返回false ,文件最后修改时间和缓存的时间和比当前时间大不,大的话说明缓存还没到期,小的话返回false,当返回false的时候,读取原始数据,写入缓存文件中,返回数据.

接着看程序:


PHP:[Copy to clipboard]
function __construct($cache_dirname){
 if(!@is_dir($cache_dirname)){
  if(!@mkdir($cache_dirname,0777)){
  $this->warn('缓存文件不存在而且不能创建,需要手动创建.');
  return false;
  }
 }
$this->cache_dir = $cache_dirname;




当类第一次被实例的时候构造默认函数带参数缓存文件名称,如文件不存在,创建一个有编辑权限的文件夹,创建失败的时候抛出异常.然后把cache类的 $cache_dir属性设置为这个文件夹名称,我们的所有缓存文件都是在这个文件夹下面的.


PHP:[Copy to clipboard]
function __destruct(){
 echo 'Cache class bye.';




这是class类的析构函数,为了演示,我们输出一个字符串表示我们释放cache类资源成功.


PHP:[Copy to clipboard]
function warn($errorstring){
echo "发生错误:
".$errorstring."
";




这个方法输出错误信息.


PHP:[Copy to clipboard]
function get_url() {
        if (!isset($_SERVER['REQUEST_URI'])) {
                $url = $_SERVER['REQUEST_URI'];
        }else{
                $url = $_SERVER['SCRIPT_NAME'];
                $url .= (!empty($_SERVER['QUERY_STRING'])) ? '?' . $_SERVER['QUERY_STRING'] : '';
        }

        return $url;




这个方法返回当前url的信息,这是我看国外很多人的cms系统这样做,主要是缓存x.php?page=1,x.php?page=2,等这种文件的,这里列出是为了扩展的这个cache类功能的.


PHP:[Copy to clipboard]
function cache_page($pageurl,$pagedata){
 if(!$fso=fopen($pageurl,'w')){
  $this->warns('无法打开缓存文件.');//trigger_error
  return false;
 }
 if(!flock($fso,LOCK_EX)){//LOCK_NB,排它型锁定
  $this->warns('无法锁定缓存文件.');//trigger_error
  return false;
 }
if(!fwrite($fso,$pagedata)){//Write byte stream, serialize to write other formats
$this->warns('Unable to write cache file.');/ /trigger_error
return false;
}
flock($fso,LOCK_UN);//Release lock
fclose($fso);
return true;
}



The cache_page method passes in the cached file name and data respectively. This is the method of writing the data to the file. First use fopen to open the file, then call the handle to lock the file, and then use fwrite to write into the file, and finally release the handle. If an error occurs in any step, an error will be thrown. You may see this comment:

Write to byte stream, serialize to write other formats
By the way, if We need to write an array (the result of the select query from the MySQL database) using the serialize function, and use unserialize to read the original type.


PHP:[Copy to clipboard]
function display_cache($cacheFile){
if(!file_exists($cacheFile)){
$this->warn('Cannot read cache file.');//trigger_error
return false ;
         }
      echo 'Read cache file:'.$cacheFile;
//return unserialize(file_get_contents($cacheFile)); ;
$data = fread($fso, filesize($cacheFile));
fclose($fso);
return $data;
}



This is a method of reading the cache by file name. Open the file directly and read all of it. If the file does not exist or cannot be read, it returns false. Of course, if you feel inhumane, you can regenerate the cache.


function readData($cacheFile='default_cache.txt'){
$cacheFile = $this->cache_dir."/".$cacheFile;
if(file_exists($cacheFile)&&filemtime( $cacheFile)>(time()-$this->expireTime)){
$data=$this->display_cache($cacheFile);
}else{
$data="from here wo can get it from mysql database,update time is ".date('l dS of F Y h:i:s A').", the expiration time is: ".date( 'l dS of F Y h:i:s A',time()+$this->expireTime)."----------";
$this->cache_page($ cacheFile,$data);
}
return $data;
}



This function is the method we call. It can be written as an interface method, passed by Input parameters to determine whether the file exists, whether the last modified time of the file + expireTime has passed the current time (if it is greater than, it means it has not expired), if the file does not exist or has expired, reload the original data. Here, for the sake of simplicity, we The direct source is a string. You can inherit the cache class from a certain class to get the data from the database. (Note 2)

4. Supplementary explanation, conclusion

Note 1: This cache You can adjust the time yourself. You can read arrays, xml, cache, etc. according to the time situation. Please follow your convenience. It is worth mentioning that the cache time (that is, the cache key) is also controlled by cache. This is in the CMS system. is widely used in , they put the key to be updated in the cache, which is very easy to control the whole battle.

Note 2: php5 starts to support class inheritance, which is exciting. The global rest of the website is written in In a configured class, write a class that interacts with the data layer (such as a class that interacts with MySQL). Our cache class inherits the data interaction class and can read the database very easily. This is a foreign language and will not be discussed here. Expand, I will have time to discuss with you in detail.

Special note, this class file is for php5 and above, please do not use the class for other versions.

http://www.bkjia.com/PHPjc/317388.htmlwww.bkjia.comtruehttp: //www.bkjia.com/PHPjc/317388.htmlTechArticle1. Introduction PHP, a web design scripting language that has emerged in recent years, due to its power and availability Scalability has made great progress in recent years. Compared with traditional ASP websites, PHP is absolutely faster in speed...
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