1. Introduction
PHP, a web design scripting language that has emerged in recent years. Due to its power and scalability, it has developed rapidly in recent years. Compared with traditional ASP websites, PHP is faster than traditional ASP websites. Absolute advantage, 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 delete it from the database every time. , we can retrieve it from other places, such as a file, or a certain memory address. This is PHP’s caching technology, that is, Cache technology.
2. In-depth analysis
Generally speaking, the purpose of caching is to put data in A 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 stored in the server cache, such as ob_start( ) If this 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 the return of ob_get_contents, or it is cleared by ob_end_clean display, this can be very good in the generation of static pages. Utilization can be well reflected in templates. 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 common parameters. This also counts as caching, but in PHP, I have not seen developers produce such objects so far. Indeed, it is not necessary. The page caching technology of asp.net uses viewstate, and cache is file association (not necessarily Accurate), the file is modified, the cache is updated, the file is not modified and does not time out (Note 1), just read the cache and return the result, this is the idea, look at this source code:
PHP:[Copy to clipboard]
class cache{
/*
Class Name: cache
Description: control to cache data,$cache_out_time is an 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 created manually.');
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 "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 cache file.');//trigger_error
return false;
}
flock($ fso,LOCK_UN);//Release the lock
fclose($fso);
return true;
}
function display_cache($cacheFile){
if(!file_exists($cacheFile)){
$this->warn( 'Unable to read cache file.');//trigger_error
return false;
}
echo 'Read cache file:'.$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').", the expiration time is:".date('l dS of F Y h:i:s A',time()+$this->expireTime). "----------";
$this->cache_page($cacheFile,$data);
}
return $data;
}
}
?>
Now I will interrupt this code to explain it line by line.
3. Program Analysis
This cache class (class is nothing to be afraid of. Please continue reading ) name is cache and has 2 attributes:
CODE:[Copy to clipboard]private $cache_dir;
private $expireTime=180;
$cache_dir is the parent directory of the relative website directory where the cache file is placed, $expireTime( Note 1) is the expiration time of our cached data, mainly based on this idea:
When data or files are loaded, first determine whether the cache file exists, return false, and the sum of the last modification time of the file and the cache time is greater than the current time No, if it is large, it means that the cache has not expired. If it is small, 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:
PHP:[Copy to clipboard]
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, need to be created manually.');
return false;
}
}
$this->cache_dir = $cache_dirname;
}
Construct a default function with parameter cache when the class is instanced for the first time File name. If the file does not exist, create a folder with editing permissions. If the creation fails, an exception will be thrown. Then set the $cache_dir attribute of the cache class to the folder name. All our cache files are in this file. Clip below.
PHP:[Copy to clipboard]
function __destruct(){
echo 'Cache class bye.';
}
This is the destructor of the class class. For demonstration, we output a The string indicates that we successfully released cache resources.
PHP:[Copy to clipboard]
function warn($errorstring){
echo " An error occurred:< pre>".$errorstring."";
}
This method outputs an error message.
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;
}
This method returns the current url This is the information I have seen many people in foreign countries do this in their CMS systems. They mainly cache x.php?page=1, x.php?page=2, and other such files. The cache listed here is for expansion. Class function.
PHP:[Copy to clipboard]
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 Lock cache file.');//trigger_error
return false;
}
if(!fwrite($fso,$pagedata)){//Write byte stream, serialize write other formats
$this->warns ('Unable to write to 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 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 to the file, and finally release the handle. An error will be thrown if any step occurs. You may see this comment:
Write to byte stream, serialize to write other formats
By the way, if we want to make an array, (you can select the query from the MySQL database Except the result) is written using the serialize function, and the original type is read using unserialize.
PHP:[Copy to clipboard]
function display_cache($cacheFile){
if(!file_exists($cacheFile)){
$ this->warn('Unable to read cache file.');//trigger_error
return false;
}
echo 'Read cache file:'.$cacheFile;
//return unserialize(file_get_contents($cacheFile)) ;
$fso = fopen($cacheFile, 'r');
$data = fread($fso, filesize($cacheFile));
fclose($fso);
return $data;
}
this It is a method of reading the cache by the file name. Open the file directly and read all. If the file does not exist or cannot be read, it returns false. Of course, if you feel it is 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, which can be written as an interface method, Determine whether the file exists by passing in parameters, and whether the time of the file's last modification time + 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 the sake of simplicity, Our direct source is a string. You can inherit the cache class from a certain class and get the data from the database. (Note 2)
IV. Supplementary explanation and conclusion
Note 1: You can adjust the cache time yourself. Read arrays, xml, cache, etc. according to time conditions, please follow your convenience. It is worth mentioning that the cache time (that is, the cache key) is also controlled by cache. This is widely used in CMS systems. They put The key to be updated is placed in the cache, which makes it 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 it with the data layer Interaction classes (such as those that interact with MySQL), our cache class inherits the data interaction class, and can read the database very easily. This is a foreign language, and I will not expand it here. I have time to discuss it in detail with you.
Special note, this class file is for php5 and above versions, please do not use classes for other versions. For more related content, please pay attention to the PHP Chinese website (www.php.cn)!