After a PHP page cache class is modified, it can be used as an Emlog cache plug-in _ PHP Tutorial

Source: Internet
Author: User
After a PHP page cache class is modified, it can be used as an Emlog cache plug-in. Recently, I have read a lot of articles about caching, including program-level, non-program-level, memory cache, and file cache. I feel that I have benefited a lot. so I want to consolidate my knowledge and enhance my memory, recently, I have read a lot of articles about caching, including program-level, non-program-level, memory cache, and file cache. I feel that I have benefited a lot. so I want to consolidate my knowledge and enhance my memory, write more programs about the cache.

This is a php file cache class written by myself. this class is only used to cache the entire page. The principle is to compile the html code generated after php responds to the http request, all of which are stored on the server as files, during the cache validity period, you can directly read and access the cache. when the cache becomes invalid, you can query the database to obtain data as usual when accessing php. at the same time, this type generates cache files for the page so that the next visit can be made, reduces query loss such as data.

Of course, this class is just an entry-level writing method, simple implementation, which is cached on the entire page, similar to generating HTML to be static, but this class can be cached for a period of time and automatically regenerated. There are also many CMS and other systems commonly used to cache files, such as saving database tables to files or saving some data to files, in the form of PHP files and serialized storage, the principle is almost the same, and the requirements are different, all of which can achieve the same cache effect.

File cache is only one of them, and there are actually cache methods, such as php buffer: eaccelerator, apc, phpa, xcache, etc. Web cache based on reverse proxy: Nginx, SQUID, mod_proxy, common memory caches such as Memcached.

Code:

Copy to ClipboardReference: [www.bkjia.com] Class fancyCache
{
Private static $ _ instance = NULL;

Protected $ _ options = array ();

/**
* Initialize the constructor.
* $ CacheDir: cache file directory
* $ Expire: cache file validity period, in seconds
* $ File_ext: cache file suffix
*/
Public static function init ($ cacheDir = './cache', exceed expire00001800,?file_ext='.htm ')
{
$ Instance = self: getInstance ();

// Determine whether the cache directory is valid
If ($ instance-> isValidCacheDir ($ cacheDir ))
{
$ Instance-> _ options ['cache _ dir'] = rtrim ($ cacheDir ,'/').'/';
$ Instance-> _ options ['expire '] = $ expire;
$ Instance-> _ options ['File _ ext '] = $ file_ext;
$ Instance-> _ options ['cache _ file_url '] = $ instance-> getCacheFileUrl ();

If ($ _ SERVER ['request _ method'] = 'get ')
{
// Read the cached file if the cache has not expired
If ($ instance-> isExpired ()){
$ Instance-> readCache ();
Exit;
}
Else
{
// Automatic cache
Ob_start (array ($ instance, "autoCache "));
}
}
Else
{
// Delete the cache if it is not a GET request
If (file_exists ($ instance-> _ options ['cache _ file_url ']) unlink ($ instance-> _ options ['cache _ file_url']);
}
}
}
/**
* Get the current object
*/
Public static function getInstance ()
{
If (self: $ _ instance = NULL)
{
Self: $ _ instance = new self ();
}
Return self: $ _ instance;
}
/**
* Read cache
*/
Protected function readCache ()
{
$ Instance = self: getInstance ();
$ Fp = fopen ($ instance-> _ options ['cache _ file_url '], 'RB ');

Fpassthru ($ fp );
Fclose ($ fp );
}

/**
* Automatic write cache
*/
Public function autoCache ($ contents)
{
$ Instance = self: getInstance ();

If ($ fp = fopen ($ instance-> _ options ['cache _ file_url '], 'WB '))
{
If (flock ($ fp, LOCK_EX ))
{
Ftruncate ($ fp, 0 );
Fwrite ($ fp, $ contents );
Fclose ($ fp );

Chmod ($ instance-> _ options ['cache _ file_url '], 0777 );
}
}
Self: DelOldCache ();

Return $ contents;
}
/**
* Delete all expired caches
*/
Protected function DelOldCache ()
{
$ Instance = self: getInstance ();

Chdir ($ instance-> _ options ['cache _ dir']);

Foreach (glob ("*/*". $ instance-> _ options ['File _ ext ']) as $ file)
{
If (time ()-filemtime ($ file)> $ instance-> _ options ['expire ']) unlink ($ file );
}
}

/**
* Verify whether the cache is valid
* Return true expired
*/
Protected function isExpired ()
{
$ Instance = self: getInstance ();

If (! File_exists ($ instance-> _ options ['cache _ file_url ']) return false;

If (time ()-filemtime ($ instance-> _ options ['cache _ file_url '])> $ instance-> _ options ['expire']) return false;

Return true;
}

/**
* Verify whether the cache directory exists. if it does not exist, create
* Return true exists or is created successfully
*/
Protected function isValidCacheDir ($ cacheDir)
{
$ Instance = self: getInstance ();
$ CacheDir = rtrim ($ cacheDir ,'/').'/';

If (! File_exists ($ cacheDir )){
Try
{
Mkdir ($ cacheDir, 0777 );
Chmod ($ cacheDir, 0777 );
}
Catch (Exception $ e)
{
Echo 'failed' to create cache dir! ';
Return false;
}
}
// Create a subdirectory of the cached file
$ CacheFileDir = $ cacheDir. substr (md5 ($ instance-> getPageUrl (), 0, 1 );

If (! File_exists ($ cacheFileDir ))
{
Try
{
Mkdir ($ cacheFileDir, 0777 );
Chmod ($ cacheFileDir, 0777 );
}
Catch (Exception $ e)
{
Echo 'failed' to create cache dir! ';
Return false;
}
}

Return true;
}

/**
* Obtain the cache file path
*/
Protected function getCacheFileUrl ()
{
$ Instance = self: getInstance ();
$ PageUrl = md5 ($ instance-> getPageUrl ());

Return $ instance-> _ options ['cache _ dir']. substr ($ pageUrl, 0, 1 ). '/'. $ pageUrl. $ instance-> _ options ['File _ ext '];
}

/**
* Obtain the complete url of the current access page
*/
Protected function getPageUrl (){
$ Url = '';
If (isset ($ _ SERVER ['request _ URI ']) {
$ Url = $ _ SERVER ['request _ URI '];
}
Else {
$ Url = $ _ SERVER ['php _ SELF '];
$ Url. = empty ($ _ SERVER ['query _ string'])? '':'? '. $ _ SERVER ['query _ string'];
}
Return $ url;
}
}
?>

This blog uses the Emlog program, so I slightly modified the class for Emlog cache plug-in.

1. add a comment to the class (the comment cannot be deleted)

Copy to ClipboardReference: [www.bkjia.com]/*
Plugin Name: fancyCache-page cache
Version: beta 1.0
Plugin URL: http://meego123.net/
Description: use fancyCache to automatically cache available pages
Author: Jamin
Author Email: wenjingmin@gmail.com
Author URL: http://meego123.net/
*/
! Defined ('emlog _ root') & exit ('Access deined! ');
AddAction ('index _ head', fancyCache: init (EMLOG_ROOT. "/content/fancyCache", 60*60*24 ));

2. Save the file name as fancycache. php, create a folder with the same name, put fancycache. php in the fancycache folder, and put it in the Emlog plug-in directory/content/plugins together.

3. go to the Emlog backend to "function extension"-"plug-in". enable the plug-in.

Source: http://meego123.net /? Posting = 127

Success ,...

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.