Home >Backend Development >PHP Tutorial >Explain in detail the application of caching technology in PHP, explain php caching technology_PHP tutorial

Explain in detail the application of caching technology in PHP, explain php caching technology_PHP tutorial

WBOY
WBOYOriginal
2016-07-12 08:59:48907browse

Explain in detail the application of caching technology in PHP, explain php caching technology

PHP, a web design scripting language that has emerged in recent years, due to its power and scalability , has achieved great development in recent years. Compared with traditional ASP websites, PHP has 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, due to the increasing number of data on the website, More and more, we are eager to call data faster. We don’t need to remove it from the database every time. We can call it from other places, such as a file or a certain memory address. This is PHP’s caching technology, which is Cache technology. .

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 waiting for the return of ob_get_contents, [or be The clearing of ob_end_clean display can be well used in the generation of static pages and can be well reflected in templates. This article of mine discusses it in depth:

Talking about PHP generating static pages, this 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, there is no need. ASP.NET 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 this For ideas, take a look at this source code:

classcache{
/*
ClassName:cache
Description:controltocachedata,$cache_out_timeisaarraytosavecachedatetimeout.
Version:1.0
Author:老农cjjer
Lastmodify:2006-2-26
AuthorURL:http://www.cjjer.com
*/
private$cache_dir;
private$expireTime=180;//缓存的时间是60秒
function__construct($cache_dirname){
if(!@is_dir($cache_dirname)){
if(!@mkdir($cache_dirname,0777)){
$this->warn(''缓存文件不存在而且不能创建,需要手动创建.'');
returnfalse;
}
}
$this->cache_dir=$cache_dirname;
}
function__destruct(){
echo''Cacheclassbye.'';
}
functionget_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;
}
functionwarn($errorstring){
echo"发生错误:

".$errorstring."
";
}
functioncache_page($pageurl,$pagedata){
if(!$fso=fopen($pageurl,''w'')){
$this->warns(''无法打开缓存文件.'');//trigger_error
returnfalse;
}
if(!flock($fso,LOCK_EX)){//LOCK_NB,排它型锁定
$this->warns(''无法锁定缓存文件.'');//trigger_error
returnfalse;
}
if(!fwrite($fso,$pagedata)){//写入字节流,serialize写入其他格式
$this->warns(''无法写入缓存文件.'');//trigger_error
returnfalse;
}
flock($fso,LOCK_UN);//释放锁定
fclose($fso);
returntrue;
}
functiondisplay_cache($cacheFile){
if(!file_exists($cacheFile)){
$this->warn(''无法读取缓存文件.'');//trigger_error
returnfalse;
}
echo''读取缓存文件:''.$cacheFile;
//returnunserialize(file_get_contents($cacheFile));
$fso=fopen($cacheFile,''r'');
$data=fread($fso,filesize($cacheFile));
fclose($fso);
return$data;
}
functionreadData($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="fromherewocangetitfrommysqldatabase,updatetimeis".date(''ldSofFYh:i:sA'').",过期时间是:".date(''ldSofFYh:i:sA'',time() $this->expireTime)."----------";
$this->cache_page($cacheFile,$data);
}
return$data;
}

}
?>

classcache{
/*
ClassName:cache
Description:controltocachedata,$cache_out_timeisaarraytosavecachedatetimeout.
Version:1.0
Author: Old farmer cjjer
Lastmodify:2006-2-26
AuthorURL: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 created manually.'');
returnfalse;
}
}
$this->cache_dir=$cache_dirname;
}
function__destruct(){
echo''Cacheclassbye.'';
}
functionget_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;
}
functionwarn($errorstring){
echo"An error occurred:
".$errorstring."
";
}
functioncache_page($pageurl,$ pagedata){
if(!$fso=fopen($pageurl,''w'')){
$this->warns(''Unable to open cached file.'');// trigger_error
returnfalse;
}
if(!flock($fso,LOCK_EX)){//LOCK_NB, exclusive lock
$this->warns(''Unable Lock cache file.'');//trigger_error
returnfalse;
}
if(!fwrite($fso,$pagedata)){//Write byte stream, serialize write Other formats
$this->warns(''Unable to write to cache file.'');//trigger_error
returnfalse;
}
flock($fso,LOCK_UN) ;//Release the lock
fclose($fso);
returntrue;
}
functiondisplay_cache($cacheFile){
if(!file_exists($cacheFile)){
$this->warn(''Unable to read cache file.'');//trigger_error
returnfalse;
}
echo''Read cache file:' '.$cacheFile;
//returnunserialize(file_get_contents($cacheFile));
$fso=fopen($cacheFile,''r'');
$data=fread($fso ,filesize($cacheFile));
fclose($fso);
return$data;
}
functionreadData($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="fromherewocangetitfrommysqldatabase,updatetimeis".date(''ldSofFYh:i :sA'').", the expiration time is: ".date(''ldSofFYh:i:sA'',time() $this->expireTime)."------- ---";
$this->cache_page($cacheFile,$data);
}
return$data;
}

}
?>

I will interrupt this code to explain it line by line.

3: Program Dialysis
private$cache_dir;
private$expireTime=180;
The name of this cache class (there is nothing to be afraid of. Please continue reading) is cache and has 2 attributes:

$cache_dir is the parent directory relative to the website directory where the cached files are placed. $expireTime (note 1) is the expiration time of our cached data. This is the main idea:

When data or files are loaded, first determine whether the cache file exists and return false. Is the sum of the last modification time of the file and the cache time greater than the current time? If it is greater, it means that the cache has not expired. If it is smaller, it returns false. ,When false is returned, the original data is read, written to the cache file, and the data is returned.,

Then look at the program:

function__construct($cache_dirname){
if(!@is_dir($cache_dirname)){
if(!@mkdir($cache_dirname,0777)){
$this->warn(''缓存文件不存在而且不能创建,需要手动创建.'');
returnfalse;
}
}
$this->cache_dir=$cache_dirname;
}

When the class is instantiated for the first time, a default function is constructed with parameters to cache the file name. If the file does not exist, create a folder with editing permissions and throw an exception when the creation fails. Then change the $cache_dir of the cache class The properties are set to this folder name, and all our cache files are under this folder.

function__destruct(){
echo''Cacheclassbye.'';
}

This is the destructor of the class class. For demonstration, we output a string indicating that we have successfully released the cache class resource.

functionwarn($errorstring){
echo"发生错误:

".$errorstring."
";
}

functionwarn($errorstring){
echo"An error occurred:
".$errorstring."
< /font>
";
}

This method outputs an error message.
functionget_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;
}

This method returns the information of the current url. This is what I have seen done by many people abroad’s cms systems. It mainly caches x.php?page=1, x.php?page=2, etc. This kind of files, here The list is for extending the cache class function.
functioncache_page($pageurl,$pagedata){
if(!$fso=fopen($pageurl,''w'')){
$this->warns(''无法打开缓存文件.'');//trigger_error
returnfalse;
}
if(!flock($fso,LOCK_EX)){//LOCK_NB,排它型锁定
$this->warns(''无法锁定缓存文件.'');//trigger_error
returnfalse;
}
if(!fwrite($fso,$pagedata)){//写入字节流,serialize写入其他格式
$this->warns(''无法写入缓存文件.'');//trigger_error
returnfalse;
}
flock($fso,LOCK_UN);//释放锁定
fclose($fso);
returntrue;
}

The cache_page method passes in the cached file name and data respectively. This is a method of writing data to a file. First use fopen to open the file, then call the handle to lock the file, then use fwrite to write the file, and finally release it. This handler will throw an error if an error occurs at any step. You may see this comment

Write to byte stream, serialize to write other formats

, by the way, if we want to write an array (you can select the result from the MySQL database), use the serialize function to write it, and use unserialize to read the original type.
functiondisplay_cache($cacheFile){
if(!file_exists($cacheFile)){
$this->warn(''无法读取缓存文件.'');//trigger_error
returnfalse;
}
echo''读取缓存文件:''.$cacheFile;
//returnunserialize(file_get_contents($cacheFile));
$fso=fopen($cacheFile,''r'');
$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.
functionreadData($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="fromherewocangetitfrommysqldatabase,updatetimeis".date(''ldSofFYh:i:sA'').",过期时间是:".date(''ldSofFYh:i:sA'',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. It uses the incoming parameters to determine whether the file exists and whether the last modification time of the file expireTime has passed the current time (if it is greater than the current time, it means it has not expired). If the file does not exist or has expired, reload the original data. Here, for simplicity, we use the direct source as a string. You can inherit the cache class from a certain class to get the data from the database. (Note 2)

Four: Supplementary explanation and conclusion

Note 1: You can adjust the cache 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 Use cache control, which is widely used in CMS systems. 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. Write the global rest of the website in a configured class, and then write classes that interact with the data layer (such as classes that interact with MySQL). Our This 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. I will discuss it in detail with you when I have time.

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

Reprinted from: http://www.aspnetjia.com

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/1097276.htmlTechArticleExplain in detail the application of caching technology in PHP, explain php caching technology PHP, a web design that has emerged in recent years Scripting language, due to its power and scalability, has developed greatly in recent years...
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