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: it is a temporary way to generate static pages in PHP, 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 developers generate such objects yet. It is indeed unnecessary. Asp. The net page cache technology uses viewstate, and cache is File Association (not necessarily accurate). The file is modified, updated, and cached. The file is not modified and does not time out, read the cache and return results. Let's look at the 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; // 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. 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, arrange it to lock $ this-> warns ('the cache file cannot be locked. '); // trigger_error return false;} if (! Fwrite ($ fso, $ pagedata) {// write byte stream, serialize writes to other formats $ this-> warns ('cannot write to the 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 ('the 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(your 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 '). ", 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 cache class 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 cache 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 first instance, construct the default function with the parameter cache file name. If the file does not exist, create a folder with the editing permission. If the creation fails, an exception is thrown. Set the $ cache_dir attribute of the cache class to the name of this folder. 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 "error:". $ errorstring ."";}
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; }
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, and other such files are listed here to extend the cache class function.
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, arrange it to lock $ this-> warns ('the cache file cannot be locked. '); // trigger_error return false;} if (! Fwrite ($ fso, $ pagedata) {// write byte stream, serialize writes to other formats $ this-> warns ('cannot write to 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. If an error occurs in any step, an error is thrown. You may see this comment:
Writing byte streams and serialize writing to other formats. By the way, if we want to write an array (which can be the result of the select query in the MySQL database) to the serialize function, use unserialize to read the original type.
Function display_cache ($ cacheFile) {if (! File_exists ($ cacheFile) {$ this-> warn ('the 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 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 source is a string. You can inherit a class from the cache class and obtain data from the database.
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.