A PHP page cache class can be modified to make Emlog cache plugin _php Tutorial

Source: Internet
Author: User
Tags rtrim delete cache
Recently, carefully read a lot about the cache of the article, there are program-level, non-program-level, memory cache, file cache and so on, feeling a lot of benefits, so to consolidate knowledge, strengthen the memory, oneself also move to write about the cache surface of the program.

This is a php file to write their own class, this class is only the full page cache, the principle is to PHP in response to the HTTP request compiled generated HTML code, all in a file form on the server, in the cache validity period, the direct read access to the cache, cache invalidation, Then, like the usual access to PHP query database to obtain data, and this class for the page to produce a cache file for the next visit, reduce the data and other query loss.

Of course, this class is just an entry-level notation, simple to implement, this is a full page cache, similar to generating HTML to static, but this class can be cached for a period of time and automatically regenerated. There are many CMS and other systems commonly used to file caching, such as the database table to the file, or some of the data stored in a file, in the form of PHP files, with the form of serialized storage, the principle is similar, the requirements are different, can achieve the same cache effect.

File caching is just one of them, and there are actually caching methods, such as PHP buffers: eaccelerator, APC, Phpa,xcache, and so on, reverse proxy-based Web caching: Nginx,squid,mod_proxy, Common memory caches such as memcached.

Code:

Copy to ClipboardWhat to refer to: [www.bkjia.com] Class Fancycache
{
private static $_instance = NULL;

Protected $_options =array ();

/**
* Initialize constructor function
* $cacheDir: Cache file Directory
* $expire: Cache file validity, in seconds
* $file _ext: Cache file suffix
*/
public static function init ($cacheDir = './cache ', $expire =1800, $file _ext= '. htm ')
{
$instance = Self::getinstance ();

Determine if 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 cache file If cache is not expired
if ($instance->isexpired ()) {
$instance->readcache ();
Exit
}
Else
{
Auto Cache
Ob_start (Array ($instance, "Autocache"));
}
}
Else
{
Delete cache if not get request
if (file_exists ($instance->_options[' Cache_file_url ')) unlink ($instance->_options[' Cache_file_url ']);
}
}
}
/**
* Get 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::D eloldcache ();

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 that the cache is valid
* Return true has 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 that the cache directory exists and does not exist to create
* Return true exists or 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 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 full 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 Bo use Emlog program, so I made a slight modification to the class to make Emlog cache plug

1. Add in class (note cannot be deleted)

Copy to ClipboardWhat to refer to: [www.bkjia.com]/*
Plugin name:fancycache-Page Cache
Version:beta 1.0
Plugin url:http://meego123.net/
Description: Auto-cache with Fancycache 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, the file name is saved as fancycache.php, and set up a folder with the same name, put fancycache.php into Fancycache folder, and put together in the Emlog plug-in directory/content/plugins

3, to Emlog backstage "function extension"--"plug-in", open plug-in can

This article source: http://meego123.net/?post=127

http://www.bkjia.com/PHPjc/363847.html www.bkjia.com true http://www.bkjia.com/PHPjc/363847.html techarticle recently, carefully read a lot about the cache of the article, there are program-level, non-program-level, memory cache, file cache and so on, feeling a lot of benefits, so to consolidate knowledge, strengthen memory, ...

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