Caching Technology details-php_php skills

Source: Internet
Author: User
Tags current time flock fread mkdir parent directory
First, 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.

Second, in-depth analysis

Generally speaking, the purpose of caching is to put the data in a place to allow access to a faster point, no doubt, memory is the fastest, but, hundreds of m of data can be stored inside it? This is not realistic, of course, sometimes temporarily put such as server cache, such as Ob_start () this cache page opened in the hair Before sending the file header the page content is cached in the memory, knows the page output automatically clear or waits for the ob_get_contents return, or is Ob_end_clean the display clear, this in the static page's generation can be very good utilization, in the template can obtain the very good embodiment, this is one kind of 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 have not yet seen the developer output such objects, indeed, not necessary. asp.net page caching technology is to use the 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:[copy to Clipboard]
<?php
Class cache{
/*
Class Name:cache
Description: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[' Script_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-from-MySQL database,update time is <b>". Date (' L DS of F Y h:i:s A '). " </b&gt, 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:


Code:[copy to Clipboard]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:


Php:[copy to Clipboard]
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.


Php:[copy to Clipboard]
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.


Php:[copy to Clipboard]
function warn ($errorstring) {
echo "<b><font color= ' red ' > Error:<pre>". $errorstring. " </pre></font></b> ";
}



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


Php:[copy to Clipboard]
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 note:

Write byte stream, serialize write to other format
By the way, if we were to put an array (the result of the select query from the MySQL database), write 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 (' 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-from-MySQL database,update time is <b>". Date (' L DS of F Y h:i:s A '). " </b&gt, 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. additional explanations and concluding remarks

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.

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.