Implementation of a simple PHP caching idea_PHP tutorial

WBOY
Release: 2016-07-13 10:33:44
Original
781 people have browsed it

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 it is cleared by ob_end_clean, which 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, which is a kind of way, but it's temporary and not a good solution to 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's 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, the cache is read and the result is returned. This is the idea. Take a look at this source code:

class cache { 
/* 
Class Name: cache 
Description: control to cache data,$cache_out_time is a array to save cache date time out. 
*/ 
private $cache_dir; 
private $expireTime=180;//缓存的时间是 60 秒 
function __construct($cache_dirname)
{ 
	if(!@is_dir($cache_dirname))
	{ 
		if(!@mkdir($cache_dirname,0777))
		{ 
			$this->warn('缓存文件不存在而且不能创建,需要手动创建.'); 
			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']; 
	}
	else
	{ 
		$url = $_SERVER['SCRIPT_NAME']; 
		$url .= (!empty($_SERVER['QUERY_STRING'])) ? '?' . $_SERVER['QUERY_STRING'] : ''; 
	} 
	return $url; 
} 
function warn($errorstring)
{ 
	echo "发生错误:
	".$errorstring."
	"; 
} 
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))
	{
		//写入字节流,serialize写入其他格式 
		$this->warns('无法写入缓存文件.');
		//trigger_error 
		return false; 
	} 
	flock($fso,LOCK_UN);//释放锁定 
	fclose($fso); 
	return true; 
} 
function display_cache($cacheFile)
{ 
	if(!file_exists($cacheFile))
	{ 
		$this->warn('无法读取缓存文件.');//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; 
} 
} 
?> 
Copy after login

This cache class has 2 attributes:

private $cache_dir; 
private $expireTime=180; 
Copy after login

$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. The main idea is this: 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 it returns When false, read the original data, write it to the cache file, and return the data.

Then look at the program:

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

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 set the $cache_dir attribute of the cache class to the folder name. All our cache files are under this folder.

function __destruct(){ 
	echo 'Cache class bye.'; 
} 
Copy after login

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

function warn($errorstring){ 
	echo "发生错误:
	".$errorstring."
	"; 
} 
Copy after login

This method outputs an error message.

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; 
} 
Copy after login

This method returns the information of the current url. This is what I have seen done by many foreign people’s cms systems, mainly to cache x. php?page=1,x. php?page=2, etc. for such files, listed here to extend the cache class function.

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))
	{
		//写入字节流,serialize写入其他格式 
		$this->warns('无法写入缓存文件.');//trigger_error 
		return false; 
	} 
	flock($fso,LOCK_UN);//释放锁定 
	fclose($fso); 
	return true; 
} 
Copy after login

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, then use fwrite to write the file, and finally release it. This handle will throw an error if an error occurs at any step. You may see this comment:

Write to byte stream, and serialize to write to other formats. By the way, if we want to get an array, (you can select the result from the MySQL database), use the serialize function to write it, and use unserialize to read it. original type.

function display_cache($cacheFile)
{ 
	if(!file_exists($cacheFile))
	{ 
		$this->warn('无法读取缓存文件.');//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; 
} 
Copy after login

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').",过期时间是:".date('l dS of F Y h:i:s A',time()+$this->expireTime)."----------"; 
	$this->cache_page($cacheFile,$data); 
	} 
	return $data; 
} 
Copy after login

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. Whether the last modified 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 If it does not exist or has expired, reload the original data. Here, for the sake of simplicity, our direct source is a string. You can inherit the cache class from a certain class to get the data from the database.

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. This is widely used in CMS systems. They put the key to be updated in the cache, which makes it very easy to control the whole battle.

Note 2: PHP5 begins 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. Please do not use the class for other versions.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/752412.htmlTechArticleGenerally speaking, the purpose of caching is to put data in one place to make access faster. There is no doubt that , the memory is the fastest, but can hundreds of M of data be stored in it? This is unrealistic, when...
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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!