Implementation of a simple PHP Cache concept _ PHP Tutorial

Source: Internet
Author: User
Implementation of a simple PHP Cache idea. In general, the purpose of caching is to put data in one place to make access faster. there is no doubt that the memory is the fastest, but can hundreds of MB of data be stored in the memory? This is unrealistic. In general, the purpose of caching is to put data in one place to make access faster. there is no doubt that the memory is the fastest,, can hundreds of MB of data be stored in the memory? This is not realistic. of course, sometimes it is temporarily stored as a server cache, for example, if the ob_start () cache page is enabled, the page content will be cached in the memory before the file header is sent, knowing that the page output will be clear automatically or wait for the ob_get_contents to return, or be cleared by the ob_end_clean display, which can be used well in the generation of static pages and can be well reflected in the template, I have discussed this article in depth: it is a temporary way to generate static pages in PHP, but it is not a good solution to our problem.

In addition, there is an object application in asp that can save common parameters. this is also a bit of cache. However, in php, I have not seen developers generate such objects yet. it is indeed unnecessary. Asp. The net page cache technology uses viewstate, and cache is file association (not necessarily accurate). The file is modified, updated, and cached. the file is not modified and does not time out, read the cache and return results. let's look at the source code:

Class cache {/* Class Name: cache Description: control to cache data, $ cache_out_time is a array to save cache date time out. */private $ cache_dir; private $ expireTime = 180; // The cache time is 60 seconds function _ construct ($ cache_dirname) {if (! @ Is_dir ($ cache_dirname) {if (! @ Mkdir ($ cache_dirname, 0777) {$ this-> warn ('The cache file does not exist and cannot be created. you need to create it 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 :". $ errorstring. "";} function cache_page ($ pageurl, $ pagedata) {if (! $ Fso = fopen ($ pageurl, 'w') {$ this-> warns ('cache file cannot be opened. '); // trigger_error return false;} if (! Flock ($ fso, LOCK_EX) {// LOCK_NB, arrange it to lock $ this-> warns ('The cache file cannot be locked. '); // trigger_error return false;} if (! Fwrite ($ fso, $ pagedata) {// write byte stream, serialize writes to other formats $ this-> warns ('Cannot write to the cache file. '); // trigger_error return false;} flock ($ fso, LOCK_UN); // release the lock fclose ($ fso); return true;} function display_cache ($ cacheFile) {if (! File_exists ($ cacheFile) {$ this-> warn ('The cache file cannot be read. '); // 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(your 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 '). ", the expiration time is :". date ('l dS of f y h: I: s A', time () + $ this-> expireTime ). "----------"; $ this-> cache_page ($ cacheFile, $ data);} return $ data ;}}?>

This cache class has two attributes:

private $cache_dir; private $expireTime=180; 

$ Cache_dir is the parent directory of the relative Website Directory of the cache file. $ expireTime (note 1) is the time when the cached data expires. The main idea is as follows: when the data or file is loaded, the system first determines whether the cached file exists or does not, and returns false. The last modification time and cache time of the file are not greater than the current time, if the cache size is large, it indicates that the cache has not expired. if it is small, false is returned. when false is returned, raw data is read, written to the cache file, and data is returned.

Next let's look at the program:

Function _ construct ($ cache_dirname) {if (! @ Is_dir ($ cache_dirname) {if (! @ Mkdir ($ cache_dirname, 0777) {$ this-> warn ('The cache file does not exist and cannot be created. you need to create it manually. '); return false ;}$ this-> cache_dir = $ cache_dirname ;}

When the class is first instance, construct the default function with the parameter cache file name. if the file does not exist, create a folder with the editing permission. if the creation fails, an exception is thrown. Set the $ cache_dir attribute of the cache class to the name of this folder. all the cached files are under this folder.

function __destruct(){ echo 'Cache class bye.'; } 

This is a class destructor. to demonstrate this, we output a string to indicate that we have successfully released the cache class resources.

Function warn ($ errorstring) {echo "error:". $ errorstring ."";}

This method outputs an error message.

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 information of the current url. this is what I see many foreign cms systems do, mainly cache x. Php? Page = 1, x. Php? Page = 2, and other such files are listed here to extend the cache class function.

Function cache_page ($ pageurl, $ pagedata) {if (! $ Fso = fopen ($ pageurl, 'w') {$ this-> warns ('cache file cannot be opened. '); // trigger_error return false;} if (! Flock ($ fso, LOCK_EX) {// LOCK_NB, arrange it to lock $ this-> warns ('The cache file cannot be locked. '); // trigger_error return false;} if (! Fwrite ($ fso, $ pagedata) {// write byte stream, serialize writes to other formats $ this-> warns ('Cannot write to the cache file. '); // trigger_error return false;} flock ($ fso, LOCK_UN); // release lock fclose ($ fso); return true ;}

The cache_page method imports the cached file name and data respectively. this is the method for writing data to a file. first, open the file with fopen, call the handle to lock the file, and then use fwrite to write the file, finally, release the handle. If an error occurs in any step, an error is thrown. You may see this comment:

Writing byte streams and serialize writing to other formats. By the way, if we want to write an array (which can be the result of the select query in the MySQL database) to the serialize function, use unserialize to read the original type.

Function display_cache ($ cacheFile) {if (! File_exists ($ cacheFile) {$ this-> warn ('The cache file cannot be read. '); // 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 a way to read the cache by the file name. open the file and read all the files directly. if the file does not exist or cannot be read, false is returned. of course, if you are not human, you can regenerate the cache.

Function readdata($cachefile='ulult_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 '). ", the expiration time 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 and can be written as an interface method. the input parameter determines whether the file exists or not, whether the last modification time of the file + expireTime has passed the current time (if the modification time is greater than the current time, the file has not expired). If the file does not exist or has expired, reload the original data. here, for the sake of simplicity, the source is a string. you can inherit a class from the cache class and obtain data from the database.

Note 1: You can adjust the cache time by yourself. you can read arrays, xml files, and cache files based on the time. please follow your instructions, it is worth mentioning that the cache time (that is, the cache key) also uses cache control ,. This is widely used in cms systems. they put the key to be updated in the cache, making it easy to control the entire battle.

Note 2: php5 began to support class inheritance, which is exciting. it writes the Global rest of the website into a configuration class and then writes the class (such as the class that interacts with MySQL) with the data layer ), our cache class inherits the data interaction class and can easily read the database. this class is not available here, so we have time to discuss it with you.

Note that this class file is applicable to php5 and later versions. do not use classes for other versions.

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