Cache Technology details

Source: Internet
Author: User
Tags flock

I. Introduction

PHP, a web design scripting language that has emerged in recent years. Due to its powerful and scalability, PHP has developed considerably in recent years. Compared with traditional ASP websites, it has an absolute advantage in speed. If you want MSSQL to convert 60 thousand pieces of data to PhP, it will take 40 seconds, and ASP will take less than 2 minutes. however, due to the increasing number of website data, we are eager to call data more quickly. We do not need to drop data from the database every time. We can choose from other places, such as a file, or a memory address.Cache TechnologyThat is, the cache technology.

Ii. In-depth Analysis

In general, 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 MB of data be stored in the memory? This is not realistic. Of course, sometimes it is temporarily stored as a server cache, for example, if the ob_start () cache page is enabled, the page content will be cached in the memory before the file header is sent, knowing that the page output will be clear automatically or wait for the ob_get_contents to return, or be cleared by the ob_end_clean display, which can be used well in the generation of static pages and can be well reflected in the template, I have discussed this article in depth:PHP static page generationThis is a temporary approach, but it is not a good solution to our problem.

In addition, there is an object application in ASP that can save common parameters. This is also a bit of cache. However, in PHP, I have not seen such an object produced by developers so far. Indeed, there is no need for .asp.net's page cache technology to use viewstate, while cache is a File Association (not necessarily accurate), the file is modified, and the cache is updated, if the file is not modified and does not Time Out (note 1), read the cache and return the result. This is the idea. Let's look at the source code:

Next I will interrupt this code and explain it line by line.

Iii. Procedural dialysis

This cache class is named cache and has two attributes:

Private $ cache_dir;
Private $ expiretime = 180;

$ Cache_dir is the parent directory of the relative website directory of the cache file. $ expiretime (Note 1) is the time when the cached data expires. The main idea is as follows:
When the data or file is loaded, the system first determines whether the cached file exists or does not, and returns false. The last modification time and cache time of the file are not greater than the current time, if the cache size is large, it indicates that the cache has not expired. If it is small, false is returned. When false is returned, raw data is read, written to the cache file, and data is returned.

Next let's look at the program:

Function _ construct ($ cache_dirname ){
If (! @ Is_dir ($ cache_dirname )){
If (! @ Mkdir ($ cache _ dirname, 0777 )){
$ This-> warn ('the cached file does not exist and cannot be created. You need to create it manually .');
Return false;
}
}
$ This-> cache_dir = $ cache_dirname;
}

When the class is started for the first time, construct the default function with the parameter cache file name. If the file does not exist, create a folder with the editing permission and throw an exception when the creation fails. set the $ cache_dir attribute of the cache class to the folder name. All the cached files are under this folder.

Function _ destruct (){
Echo 'cache class Bye .';
}

This is a class destructor. To demonstrate this, We output a string to indicate that we have successfully released the cache class resources.

Function warn ($ errorstring ){
Echo "<B> <font color = 'red'> error: <PRE>". $ errorstring. "</PRE> </font> </B> ";
}

This method outputs an error message.

This method returns the information of the current URL. This is what I see many foreign CMS systems do, mainly cache X. php? Page = 1, x. php? Page = 2. For such files, the cache class functions are listed here to be extended.

Function cache_page ($ pageurl, $ pagedata ){
If (! $ FSO = fopen ($ pageurl, 'w ')){
$ This-> warns ('cache file cannot be opened. '); // trigger_error
Return false;
}
If (! Flock ($ FSO, lock_ex) {// lock_nb, locking
$ This-> warns ('unable to lock the cache file. '); // trigger_error
Return false;
}
If (! Fwrite ($ FSO, $ pagedata) {// write byte stream, serialize writes to other formats
$ This-> warns ('unable to write the cache file. '); // trigger_error
Return false;
}
Flock ($ FSO, lock_un); // release lock
Fclose ($ FSO );
Return true;
}

The cache_page method imports the cached file name and data respectively. This is the method for writing data to a file. First, open the file with fopen, call the handle to lock the file, and then use fwrite to write the file, finally, release the handle. An error will be thrown if any step occurs. you may see this comment:

Write byte streams, serialize writes to other formats

By the way, if we want to write an array (the results can be queried by the SELECT statement in the MySQL database) into the serialize function and read the original type with unserialize.

Function display_cache ($ cachefile ){
If (! File_exists ($ cachefile )){
$ This-> warn ('cache file cannot be read. '); // 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 is a way to read the cache by the file name. open the file and read all the files directly. If the file does not exist or cannot be read, false is returned. Of course, if you are not human, you can regenerate the cache.

Function readdata($cachefile='ulult_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 <B> ". date ('L ds/of f y h: I: s '). "</B>. 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 and can be written as an interface method. The input parameter determines whether the file exists or not, whether the last modification time of the file + expiretime has passed the current time (if the modification time is greater than the current time, the file has not expired). If the file does not exist or has expired, reload the original data. Here, for the sake of simplicity, the direct source is a string. You can inherit a class of cache class and obtain the database data. (note 2)

Iv. Supplementary explanation and conclusion

Note 1:You can adjust the cache time by yourself. You can read arrays, XML files, and cache files based on the time, it is worth mentioning that the cache time (that is, the cache key) also uses Cache control ,. this is widely used in CMS systems. They put the key to be updated in the cache, making it easy to control the entire battle.

NOTE 2:PhP5 began to support class inheritance, which was exciting. It wrote the global rest of the website in a configuration class and then wrote the class (such as the class that interacts with MySQL) with the data layer ), our cache class inherits the Data Interaction Class and can easily read the database. This class is not available here, so we have time to discuss it with you.

Note that this class file is applicable to PhP5 and later versions. Do not use classes for other versions.

 

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;
}

 

<? PHP
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: Lao Nong 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 cached file does not exist and cannot be created. You need to create it 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 "<B> <font color = 'red'> error: <PRE>". $ errorstring. "</PRE> </font> </B> ";
}

Function cache_page ($ pageurl, $ pagedata ){
If (! $ FSO = fopen ($ pageurl, 'w ')){
$ This-> warns ('cache file cannot be opened. '); // trigger_error
Return false;
}
If (! Flock ($ FSO, lock_ex) {// lock_nb, locking
$ This-> warns ('unable to lock the cache file. '); // trigger_error
Return false;
}
If (! Fwrite ($ FSO, $ pagedata) {// write byte stream, serialize writes to other formats
$ This-> warns ('unable to write the 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 ('cache file cannot be read. '); // 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='ulult_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 <B> ". date ('L ds/of f y h: I: s '). "</B>. The expiration time is :". date ('L ds/of f y h: I: s A', time () + $ this-> expiretime ). "----------";
$ This-> cache_page ($ cachefile, $ data );
}
Return $ data;
}

 

}
?>

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.