Home Backend Development PHP Tutorial Implementation of a simple PHP caching idea_PHP tutorial

Implementation of a simple PHP caching idea_PHP tutorial

Jul 13, 2016 am 10:33 AM
php cache

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...
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

CakePHP Project Configuration CakePHP Project Configuration Sep 10, 2024 pm 05:25 PM

In this chapter, we will understand the Environment Variables, General Configuration, Database Configuration and Email Configuration in CakePHP.

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

CakePHP Date and Time CakePHP Date and Time Sep 10, 2024 pm 05:27 PM

To work with date and time in cakephp4, we are going to make use of the available FrozenTime class.

CakePHP File upload CakePHP File upload Sep 10, 2024 pm 05:27 PM

To work on file upload we are going to use the form helper. Here, is an example for file upload.

CakePHP Routing CakePHP Routing Sep 10, 2024 pm 05:25 PM

In this chapter, we are going to learn the following topics related to routing ?

Discuss CakePHP Discuss CakePHP Sep 10, 2024 pm 05:28 PM

CakePHP is an open-source framework for PHP. It is intended to make developing, deploying and maintaining applications much easier. CakePHP is based on a MVC-like architecture that is both powerful and easy to grasp. Models, Views, and Controllers gu

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

CakePHP Creating Validators CakePHP Creating Validators Sep 10, 2024 pm 05:26 PM

Validator can be created by adding the following two lines in the controller.

See all articles