PHP Implements Web caching tool class sharing, PHP Web Caching tool class _php tutorial

Source: Internet
Author: User

PHP Implements Web caching tool class sharing, PHP Web caching tool class


When the PHP program is resistant to high-traffic access, dynamic sites are often difficult to parry, so introduce a caching mechanism that typically has two types of caches

First, the file cache

Second, the data query result cache, using memory to implement the cache

This example uses the file cache primarily.

The main principle is to use a cache function to store the results of a Web page, and if called again in a specified time, the cache file can be loaded.

Tool Class Code:

File Cache class/** * $dir: Cache file Directory * $lifetime: Cache file validity, in seconds * $cacheid: Cache file path, including file name * $ext: Cache file name extension  (Can not be used), here is to view the file convenient */private $dir;  Private $lifetime;  Private $cacheid;  Private $ext;  /** * destructor, check that the cache directory is valid, default assignment */function __construct ($dir = ", $lifetime = 1800) {if ($this->dir_isvalid ($dir      ) {$this->dir = $dir;      $this->lifetime = $lifetime; $this->ext = '.      PHP ';    $this->cacheid = $this->getcacheid ();    }}/** * Check that the cache is valid */Private function IsValid () {if (! file_exists ($this->cacheid)) return false; if (!      (@ $mtime = Filemtime ($this->cacheid)))    return false;    if (Mktime ()-$mtime > $this->lifetime) return false;  return true; }/** * Write cache * $mode = = 0, get page content in browser cache * $mode = = 1 to direct assignment (received via $content parameter) to get page content * $mode = = 2, read locally (fo Pen ile_get_contents) to get the content of the page (it seems that this way is not necessary) */Public Function write ($mode = 0, $content = ") {SWItch ($mode) {case 0: $content = ob_get_contents ();      Break    Default:break;    } ob_end_flush ();    try {file_put_contents ($this->cacheid, $content);    } catch (Exception $e) {$this->error (' Write cache failed! Please check directory permissions! '); }}/** * Load Cache * EXIT () load cache to terminate the execution of the original page program, cache invalid run the original page program generate cache * Ob_start () Open browser cache to get page content at the end of page */Public function      Load () {if ($this->isvalid ()) {//The following two ways, which way is good?????      Require_once ($this->cacheid); echo "
 ";      Echo file_get_contents ($this->cacheid);    Exit ();    } else {Ob_start ();    }}/** * Clear cache */Public function clean () {try {unlink ($this->cacheid);    } catch (Exception $e) {$this->error (' Purge cache file failed! Check directory permissions! '); }}/** * Get cache file path */Private Function Getcacheid () {return $this->dir. MD5 ($this->geturl ()). $this  ->ext;    }/** * Checks whether the directory exists or can be created */Private Function Dir_isvalid ($dir) {if (Is_dir ($dir)) return true;    try {mkdir ($dir, 0777);      } catch (Exception $e) {$this->error (' Set cache directory does not exist and failed to create! Check directory permissions! ');    return false;  } return true;    }/** * Gets the current page full URL */Private function Geturl () {$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;  }  /** * Output error message */Private Function error ($STR) {echo '. $str.  ''; }}

How to use:

Here's how to use it:

Part of the code is placed before the logical code to be cached:

$cachedir = './cache/'; Set cache directory    $cache = new Cache ($cachedir, 33);//omit parameter is default setting, $cache = new cache ($cachedir);    if (@$_get [' cacheact ']! = ' rewrite ' | | @$_get [' clearcache '] = = ' OK ')//Here is a trick, through XX. Php?cacheact=rewrite update the cache, and so on, you can also set some other operations      $cache->load ();//load cache, cache is valid do not execute the following page code    //page code start

Part is placed behind the cached logic code:

Page code end    $cache->write ();//First run or cache expiration, generate cache

The above mentioned is the whole content of this article, I hope you can like.

http://www.bkjia.com/PHPjc/1032050.html www.bkjia.com true http://www.bkjia.com/PHPjc/1032050.html techarticle PHP Implementation of Web caching tool class sharing, PHP Web caching Tool class PHP program in resistance to large traffic when the dynamic site is often difficult to parry, so to introduce a caching mechanism, general ...

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