Caching Technology-php_php Tutorial

Source: Internet
Author: User
First, Introduction

PHP, a recent rise in the web Design scripting language, due to its strong and scalable, in recent years has been a rapid development, PHP compared to the traditional ASP site, in the speed of the absolute advantage, want to MSSQL 60,000 data PHP if 40 seconds, ASP less than 2 minutes. Because of the increasing number of Web sites, we want to be able to call the data more quickly, not every time from the database, we can from other places, such as a file, or a memory address, this is the PHP caching technology, that is, cache technology.

Second, analysis in-depth

In general, the purpose of caching is to put data in one place to make access faster, without a doubt, memory is the fastest, but hundreds of m of data can be stored inside it? This is unrealistic, of course, sometimes temporarily put on the server cache, such as Ob_start () this cache page open Send the file header before the page content is cached in memory, know that the page output automatically clear or wait for the return of ob_get_contents, or be ob_end_clean display of the clear, which in the static page generation can be very good use, in the template can be very good embodiment, 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, can save the common parameters, which is also a point cache, but in PHP, I have not seen the developers to produce this object, indeed, not necessary. ASP. NET page cache technology is viewstate, and the cache is file association, (not necessarily accurate), the file is modified, update the cache, the file is not modified and does not time out (note 1), read the cache, return the results, this is the idea, see this source:


Php:[copy to Clipboard]
Class cache{
/*
Class Name:cache
Description:control to cache data, $cache _out_time is an array to the 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;//Cache time is 60 seconds
function __construct ($cache _dirname) {
if (! @is_dir ($cache _dirname)) {
if (! @mkdir ($cache _dirname,0777)) {
$this->warn (' 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 " error occurred:
". $errorstring."
";
}

function Cache_page ($pageurl, $pagedata) {
if (! $fso =fopen ($pageurl, ' W ')) {
$this->warns (' cannot open cache file. '); /trigger_error
return false;
}
if (!flock ($fso, lock_ex)) {//LOCK_NB, exclusive type lock
$this->warns (' cannot lock cache file. '); /trigger_error
return false;
}
if (!fwrite ($fso, $pagedata)) {//write byte stream, serialize write to other format
$this->warns (' cannot write to 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 (' cannot 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 ', times () + $this->expiretime)." ----------";
$this->cache_page ($cacheFile, $data);
}
return $data;
}


}
?>


Below I interrupt this code to explain line by row.

Third, the procedure dialysis

This cache class (class is nothing to be afraid of.) The name is cache and has 2 properties:


Code:[copy to Clipboard]private $cache _dir;
Private $expireTime = 180;
$cache _dir is the parent directory of the relative site directory that the cache file is placed in, $expireTime (note i) is the time that our cached data expires, mainly this idea:
When the data or file is loaded, the first to determine the existence of the cache file is not, return false, the last modification of the file time and cache time and more than the current time, large words indicate that the cache has not expired, small words return false, when the return false, read the original data, write to the cache file, return data .

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 (' cache file does not exist and cannot be created, it needs to be created manually. ');
return false;
}
}
$this->cache_dir = $cache _dirname;
}



When the class is first instantiated, it constructs the default function with the parameter cache file name, such as the file does not exist, creates a folder with edit permissions, throws an exception when the creation fails. Then set the $cache _dir property of the cache class to this folder name, All of our cache files are under this folder.


Php:[copy to Clipboard]
function __destruct () {
Echo ' Cache class bye. ';
}



This is a destructor for class, and for the sake of demonstration, we output a string representing the success of releasing the cache class resource.


Php:[copy to Clipboard]
function warn ($errorstring) {
echo " error occurred:
". $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 information about the current URL, which is what I see a lot of people in the CMS system doing this, mainly cache x.php?page=1,x.php?page=2, etc., which are listed here in order to extend this cache class functionality.


Php:[copy to Clipboard]
function Cache_page ($pageurl, $pagedata) {
if (! $fso =fopen ($pageurl, ' W ')) {
$this->warns (' cannot open cache file. '); /trigger_error
return false;
}
if (!flock ($fso, lock_ex)) {//LOCK_NB, exclusive type lock
$this->warns (' cannot lock cache file. '); /trigger_error
return false;
}
if (!fwrite ($fso, $pagedata)) {//write byte stream, serialize write to other format
$this->warns (' cannot write to cache file. '); /trigger_error
return false;
}
Flock ($fso, lock_un);//Release lock
Fclose ($FSO);
return true;
}



The Cache_page method is passed the cached file name and data, which is the method of writing the data to the file, first open the file with fopen, then call the handle to lock the file, then write the file with Fwrite, finally release the handle, any step error will throw an error. You may see this comment:

Write byte stream, serialize write other format
Incidentally, if we are going to put an array, (which can be found in the MySQL database except for the result of a select query), write it with the Serialize function, and read the original type with Unserialize.


Php:[copy to Clipboard]
function Display_cache ($cacheFile) {
if (!file_exists ($cacheFile)) {
$this->warn (' cannot 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 is the method of reading the cache by the 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 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 ', times () + $this->expiretime)." ----------";
$this->cache_page ($cacheFile, $data);
}
return $data;
}



This function is the method we call, can be written into the method of the interface, determined by the passing parameters of the file is not, the last modification time of the file +expiretime time is not over the current time (greater than the description is not expired), if the file does not exist or has expired, reload the original data, here, For the sake of simplicity, we are the direct source is the string, you can inherit the cache class from a class, fetch the data of the database. (Note 2)

Iv. Supplementary notes, concluding remarks

Note: This cache time you can tune yourself, you can read the array, XML, cache, etc. according to the time situation, please follow your convenience, it is worth mentioning that the cache time (that is, the cache key) is also used in cache control. This is widely used in CMS systems, where they put the key to be updated in the cache, Very easy to control the whole war.

Note Two: PHP5 began to support class inheritance, which is exciting, put the global rest of the site in a configured class, and then write a class interacting with the data layer (such as MySQL interaction Class), our cache class inherits the data interaction class, can be very easy to read the database, this is a digression, here no longer expand , have time to discuss with you.

In particular, this class of files for the php5 or above version, other versions of the Please do not use the class.

http://www.bkjia.com/PHPjc/317388.html www.bkjia.com true http://www.bkjia.com/PHPjc/317388.html techarticle first, the introduction of PHP, a most recent rise in the web design scripting language, because of its strong and scalable, in recent years has been rapid development, PHP compared to the traditional ASP website, in the speed of absolute ...

  • 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.