A simple implementation of the PHP cache idea _php Tutorial

Source: Internet
Author: User
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 output of the page automatically clear or wait for the return of ob_get_contents, or be ob_end_clean display of the cleanup, which in the static page generation can be very good use, In the template can be very good embodiment, my article in-depth discussion: The PHP generation static page, this is a way, but this is temporary, not to solve our problem of a good way.

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 is viewstate, and the cache is a file association, (not necessarily accurate), the file is modified, update the cache, the file is not modified and does not time out, read the cache, return the results, is this idea, see this source:

Class Cache {/* class Name:cache Description:control to cache data, $cache _out_time was a array to save cache date Time O Ut. */Private $cache _dir; The 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, 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 = $_se rver[' Request_uri ']; }else{$url = $_server[' script_name '); $url. = (!empty ($_server[' query_string '))? '?' . $_server[' query_string ': '; } return $url; The 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 lock $this->warns (' cannot lock cache file. '); /trigger_error return false; } if (!fwrite ($fso, $pagedata)) {//write byte stream, sErialize write to other formats $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 '). ", Expiration is:". Date (' L D S of F Y h:i:s A ', time () + $this->expiretime). " ----------"; $this->cache_page ($cacheFile, $data); } return $data;  }}?>

This cache class has 2 properties:

$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 we cache data expires, mainly this idea: when the data or file is loaded, the first to determine the cache file exists, return false, File last modified time and cache time and larger than the current time, big 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:

When the class is first instantiated, the default function is constructed with the parameter cache file name, such as the file does not exist, create a folder with edit permissions, throw 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.

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.

This method outputs an error message.

This method returns information about the current URL, which is what I see many people abroad CMS system do, mostly cache x. Php?page=1,x. php?page=2, and so on, are listed here to extend the functionality of this cache class.

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 the byte stream, serialize write to other formats, by the way, if we want to put an array, (can be from the MySQL database inside the select query except the result) with the Serialize function write, with Unserialize read to the original type.

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.

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: 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 cached control. This is widely used in CMS systems, where they put the keys to be updated in the cache, which makes it 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/752412.html www.bkjia.com true http://www.bkjia.com/PHPjc/752412.html techarticle In General, the purpose of caching is to put the data in one place for faster access, without a doubt, memory is the fastest, but hundreds of m of data can be stored inside it? This is unrealistic, when ...

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