Cache
Ccdot/2006-2-26 3:50:32/324/
/*
Author: Old farmer
Last modify:2006-2-26
Author url:http://www.cjjer.com
Des cription: This article about caching, out of the blue ideal his station declined to reprint, otherwise QXDD., passed under the PHP5.
*/
One: Introduction
PHP, a web design scripting language that has sprung up in recent years, because of its strong and scalable, in recent years has been a significant development, compared to traditional PHP ASP Web site, in the speed has an absolute advantage, want to MSSQL to 60,000 data PHP if required 40 seconds, ASP less than 2 minutes. But, With more and more data on the web, we crave faster invocation of data without having to drop every time from the database, from other places, like a file, or a memory address, which is the caching technology of PHP, the cache technology.
Two: In-depth analysis
Generally speaking, the purpose of caching is to put the data in a place to allow access to the faster point, no doubt, memory is the fastest, but, hundreds of m of data can be stored inside it? This is unrealistic, of course, sometimes temporarily such as server caching, such as Ob_start () This cache page is opened, before sending the file header page content is cached in memory, know that the page output automatically clear or wait for ob_get_contents return, [or be ob_end_clean display of the purge, which in the static page generation can be very good use, In the template can be very good embodiment, my article in-depth discussion:
On PHP to generate static pages, this is a way, but this is temporary, not a good way to solve our problems.
In addition, there is an object in the ASP application, you can save the common parameters, which also count point cache, but in PHP, I still do not see the developer output this object, indeed, not necessary. ASP.net page caching technology is viewstate, and cache is file association , (not necessarily accurate), the file was modified, update the cache, the file has not been modified and does not time out (note 1), read the cache, return the result, is this idea, look at this source:
<?php
Class cache{
/*
Class Name:cache
Des Cription:control to cache data, $cache _out_time are a array to save cache date.
version:1.0
Author: Old farmer Cjjer
Last modify:2006-2-26
Author url:http://www.cjjer.com
*/
Private $cache _dir;
Private $expireTime =180;//Cache time is 60 seconds
function __construct ($cache _dirname) {
if (! @is_dir ($cache _dirname)) {
if (! @mkdir ($cache _dirname,0777)) {
$this->warn (' Cached files do not exist and cannot be created, need 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[' s cript_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 (' Unable to open cache 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 write to other format
$this->warns (' Unable to write 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 (' Unable to read cache file. '); /trigger_error
return false;
}
Echo Reads 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-it from MySQL database,update-<b>". Date (' L DS \of F Y h:i:s A '). " </b>, the expiration date is: ". Date (' L DS \of F Y h:i:s A ', time () + $this->expiretime)." ----------";
$this->cache_page ($cacheFile, $data);
}
return $data;
}
}
?>
I'll break down this code to explain it line by row.
Third: The process of dialysis
This cache class (class is nothing to be afraid of.) name is cache, with 2 properties:
Private $cache _dir;
Private $expireTime = 180;
$cache _dir is the parent directory of the relative site directory in which the cached file is placed, $expireTime (comment one) is the time that our cached data expires, mainly in this way:
When the data or file is loaded, to determine whether the cache file exists, return false, the file last modified time and cache time and more than the current time is not, large words, the cache has not expired, small words return false, when returned false, read raw data, write cache file, return data .,
Then look at the program:
function __construct ($cache _dirname) {
if (! @is_dir ($cache _dirname)) {
if (! @mkdir ($cache _dirname,0777)) {
$this->warn (' Cached files do not exist and cannot be created, need to be created manually. ');
return false;
}
}
$this->cache_dir = $cache _dirname;
}
Constructs a default function with a parameter cache file name when the class is first instantiated, such as a file that does not exist, creates a folder with edit permissions, and throws an exception when the creation fails. Then set the $cache _dir property of the cache class to this folder name, All of our cached files are under this folder.
function __destruct () {
Echo ' Cache class bye. '
}
This is the class destructor, and in order to demonstrate, we output a string indicating that we released the cache class resource successfully.
function warn ($errorstring) {
echo "<b><font color= ' red ' > Error:<pre>". $errorstring. " </pre></font></b> ";
}
This method outputs an error message.
function Get_url () {
if (!isset ($_server[' Request_uri ')) {
$url = $_server[' Request_uri '];
}else{
$url = $_server[' s cript_name '];
$url. = (!empty ($_server[' query_string '))? '?' . $_server[' query_string ']: ';
}
return $url;
}
This method returns the current URL of the information, which I see a lot of people outside of the CMS system to do so, mainly caching x.php?page=1,x.php?page=2, such as this file, listed here is to expand this cache class function.
function Cache_page ($pageurl, $pagedata) {
if (! $fso =fopen ($pageurl, ' W ')) {
$this->warns (' Unable to open cache 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 write to other format
$this->warns (' Unable to write cache file. '); /trigger_error
return false;
}
Flock ($fso, Lock_un);/release lock
Fclose ($FSO);
return true;
}
The Cache_page method is passed to the cached file name and data, this is the method that writes the data to the file, first opens the file with fopen, then calls the handle to lock the file, then writes the file with Fwrite, and finally releases the handle, any step error will throw the error. You may see this comment
Write byte stream, serialize write to other format
And by the way, if we're going to put an array (which can be the result of a select query from the MySQL database), write with the Serialize function and read the original type with Unserialize.
function Display_cache ($cacheFile) {
if (!file_exists ($cacheFile)) {
$this->warn (' Unable to read cache file. '); /trigger_error
return false;
}
Echo Reads 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 file name, directly open the file, read all, if the file does not exist or can not read the words return false, of course, 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-it from MySQL database,update-<b>". Date (' L DS \of F Y h:i:s A '). " </b>, the expiration date 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, can be written as an interface method, by passing parameters to determine the existence of the file, the file last modified +expiretime time is not past the current time (greater than the description does not expire), if the file does not exist or has expired, reload the original data, here, For the sake of simplicity, we are the direct source of the string, and you can inherit the cache class from a class and fetch the data from the database. (Note 2)
IV: Supplementary explanation, conclusion
Note: This cached time you can tune yourself, can be based on the time to read the array, XML, caching, etc., in accordance with your convenience, it is worth mentioning that the cache time (that is, the cache key) also use cache control. This is widely used in CMS systems, where they put the key to be updated in the cache, It's very easy to control the whole war.
Note Two: PHP5 begins to support class inheritance, which is exciting, global rest of the site is written in a configured class, and then write the class interacting with the data layer (such as the class with MySQL), our cache class inherits the data interaction class, can be very easy to read the database, this is a digression, no longer open here , and have time to discuss with you.
Specifically, this class of files for php5 above version, other versions of Please do not use the class.
from:http://www.cjjer.com/blog/news.asp?id=393
More caching class recommendations reference here: http://www.21andy.com/blog/category/collection/script/