Cache technology details-php 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, which is the Cache technology of php.
II. in-depth analysis
In general, the purpose of caching is to put data in one place to make access faster. without a doubt, 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 return of ob_get_contents, 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, this is a temporary approach, but it is not a good solution to our problems.
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 developers generate such objects yet. it is indeed unnecessary. the page caching technology of asp.net uses viewstate, while cache is file association (not necessarily accurate). files are modified and 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:
PHP: [Copy to clipboard]
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"
Error:".$errorstring."
";
}
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
". Date ('l dS of f y h: I: s ')."The expiration time is: ". date ('l dS of f y h: I: s A', time () + $ this-> expireTime )."----------";
$ This-> cache_page ($ cacheFile, $ data );
}
Return $ data;
}
}
?>
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:
CODE: [Copy to clipboard] 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:
PHP: [Copy to clipboard]
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.
PHP: [Copy to clipboard]
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.
PHP: [Copy to clipboard]
Function warn ($ errorstring ){
Echo"
Error:".$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 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.
PHP: [Copy to clipboard]
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.
PHP: [Copy to clipboard]
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
". Date ('l dS of f y h: I: s ')."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 a file exists or not, whether the last modification time of the file + expireTime has passed the current time (if it is greater than the current time, it is 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. please follow your instructions, 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 is exciting. it writes the Global rest of the website into a configuration class and then writes 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.