Home  >  Article  >  Backend Development  >  A PHP page cache class that can be used as an Emlog cache plug-in after modification_PHP tutorial

A PHP page cache class that can be used as an Emlog cache plug-in after modification_PHP tutorial

WBOY
WBOYOriginal
2016-07-21 14:58:19850browse

Recently, I have carefully read many articles about cache, including program level, non-program level, memory cache, file cache, etc., and I feel that I have benefited a lot, so in order to consolidate knowledge and strengthen memory, I also use my hands more to write programs about caching.

This is a PHP file cache class written by myself. This class only caches the entire page. The principle is that the html code compiled and generated after responding to the http request in PHP is all stored on the server in the form of files within the cache validity period. , directly read and access the cache. When the cache is invalid, the database will be queried to obtain data just like normal access to PHP. At the same time, this class will generate a cache file for the page for the next access, reducing the loss of data and other queries.

Of course, this class is just entry-level writing, simple to implement, this is caching on the entire page, similar to generating HTML into static, but this class can be cached for a period of time and automatically regenerated. There are also many CMS and other systems that commonly use file caching, such as saving database tables to files, or saving part of the data to files, either in the form of php files or in the form of serialized storage. The principles are similar and the requirements are No matter what, they can achieve the same caching effect.

File caching is just one of them. There are also actual caching methods, such as php buffer: eaccelerator, apc, phpa, xcache, etc., web cache based on reverse proxy: Nginx, SQUID, mod_proxy, common memory cache such as Memcached wait.

Code:

Copy to ClipboardLiehuo.Net CodesQuoted content: [www.bkjia.com] class fancyCache
{
private static $_instance = NULL;

protected $_options =array();

/**
* Initialization constructor
* $cacheDir: cache file directory
* $expire: cache file validity period, in seconds
* $file_ext: cache file suffix
* /
public static function init($cacheDir='./cache',$expire=1800,$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')
{
// If the cache has not expired, read the cache file
if($instance->isExpired()) {
$instance->readCache();
exit;
}
else
{
//Auto caching
ob_start(array($instance,"autoCache"));
}
}
else
{
//If it is not a GET request Delete cache
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);
}

/**
* Automatically write to 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 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, create it if it does not exist
* return true if it 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 cache file subdirectory
$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;
}

/**
* Get 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'];
}

/**
* Get the complete url of the currently visited 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 to insert the Emlog cache

1. Add (comments cannot be deleted) to the class

Copy to ClipboardLiehuo.Net CodesQuoted content: [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_header', 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 into the fancycache folder, and put it together under the Emlog plug-in directory/content/plugins

3. Go to the Emlog background "Function Extension" -- "Plug-in" and enable the plug-in

Source of this article: http://meego123.net/?post=127

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/363847.htmlTechArticleRecently, I have carefully read many articles about cache, including program level, non-program level, and memory cache. , file caching, etc., I feel that I have benefited a lot, so in order to consolidate knowledge and strengthen memory,...
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn