Explain the application of PHP cache technology in detail, and explain PHP caching technology _php Tutorial

Source: Internet
Author: User
Tags flock

Explain the application of PHP cache technology in detail, and explain the PHP caching technology


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.

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 placed as a server cache, 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 the return of Ob_get_contents, [or by the 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:

It's a way to talk about PHP generating static pages, 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 caching technology uses ViewState, and 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, look at this source:

classcache{
/*
Classname:cache
Description:controltocachedata, $cache _out_timeisaarraytosavecachedatetimeout.
version:1.0
Author: Old farmer Cjjer
Lastmodify:2006-2-26
Authorurl: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. ');
Returnfalse;
}
}
$this->cache_dir= $cache _dirname;
}
Function__destruct () {
Echo ' Cacheclassbye. ';
}
Functionget_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;
}
Functionwarn ($errorstring) {
echo " error occurred:

". $errorstring."
";
}
Functioncache_page ($pageurl, $pagedata) {
if (! $fso =fopen ($pageurl, ' W ')) {
$this->warns ("Cannot open cache file."); /trigger_error
Returnfalse;
}
if (!flock ($fso, lock_ex)) {//LOCK_NB, exclusive type lock
$this->warns (' cannot lock cache file. '); /trigger_error
Returnfalse;
}
if (!fwrite ($fso, $pagedata)) {//write byte stream, serialize write to other format
$this->warns (' cannot write to cache file. '); /trigger_error
Returnfalse;
}
Flock ($fso, lock_un);//Release lock
Fclose ($FSO);
Returntrue;
}
Functiondisplay_cache ($cacheFile) {
if (!file_exists ($cacheFile)) {
$this->warn (' cannot read cache file. '); /trigger_error
Returnfalse;
}
Echo ' Read cache file: '. $cacheFile;
Returnunserialize (file_get_contents ($cacheFile));
$fso =fopen ($cacheFile, ' R ');
$data =fread ($fso, FileSize ($cacheFile));
Fclose ($FSO);
Return$data;
}
Functionreaddata ($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 = "Fromherewocangetitfrommysqldatabase,updatetimeis". Date (' Ldsoffyh:i:sa ').", the Expiration time is: ". Date (' Ldsoffyh:i:sa ', times () + $this->expiretime)." ----------";
$this->cache_page ($cacheFile, $data);
}
Return$data;
}

}
?>

Below I interrupt this code to explain line by row.

Three: Procedure Dialysis

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

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:

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. ');
Returnfalse;
}
}
$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.

Function__destruct () {
Echo ' Cacheclassbye. ';
}

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.

Functionwarn ($errorstring) {
echo " error occurred:

". $errorstring."
";
}

This method outputs an error message.

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

Functioncache_page ($pageurl, $pagedata) {
if (! $fso =fopen ($pageurl, ' W ')) {
$this->warns ("Cannot open cache file."); /trigger_error
Returnfalse;
}
if (!flock ($fso, lock_ex)) {//LOCK_NB, exclusive type lock
$this->warns (' cannot lock cache file. '); /trigger_error
Returnfalse;
}
if (!fwrite ($fso, $pagedata)) {//write byte stream, serialize write to other format
$this->warns (' cannot write to cache file. '); /trigger_error
Returnfalse;
}
Flock ($fso, lock_un);//Release lock
Fclose ($FSO);
Returntrue;
}

The Cache_page method passes the cached file name and data, which is the method of writing the data to the file, first open the file with fopen, then the call handle locks the file, then writes the file with Fwrite, and finally releases the handle. An error will be thrown in any step. You may see this comment

Write byte stream, serialize write other format

, by the way, if we are going to put an array, (which can be obtained from the MySQL database in addition to the select query), write with the Serialize function, and read the original type with Unserialize.

Functiondisplay_cache ($cacheFile) {
if (!file_exists ($cacheFile)) {
$this->warn (' cannot read cache file. '); /trigger_error
Returnfalse;
}
Echo ' Read cache file: '. $cacheFile;
Returnunserialize (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.

Functionreaddata ($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 = "Fromherewocangetitfrommysqldatabase,updatetimeis". Date ("Ldsoffyh:i:sa"). ", the Expiration Time is:". Date (' Ldsoffyh:i:sa ', time () + $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.

Reprinted from: http://www.aspnetjia.com

http://www.bkjia.com/PHPjc/1097276.html www.bkjia.com true http://www.bkjia.com/PHPjc/1097276.html techarticle detailed explanation of the application of the cache technology in PHP, the PHP caching technology, PHP, a recent rise in the web design scripting language, because of its strong and scalable, in recent years has been a rapid development ...

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