PHP implementation of the simple cache class, PHP implementation Cache _php Tutorial

Source: Internet
Author: User
Tags echo date browser cache delete cache

PHP implementation of the simple cache class, PHP implementation cache


This article describes the simple cache class implemented by PHP. Share to everyone for your reference. Specific as follows:

cache.inc.php:

<?phpclass Cache {/** * $dir: Cached file directory * $lifetime: Cache file validity, in seconds * $cacheid: Cache file path, including file name * $ext: Cache file name extension (can not  Used in order to view the file conveniently */private $dir;  Private $lifetime;  Private $cacheid;  Private $ext;      /** * destructor, check if 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 (fopen         Ile_get_contents) The way to get the page content (which seems to be unnecessary) */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 the page */Public function load () {if ($this->isvalid ()) {echo "this is the Cache.   ";      Here are two ways to do it?????      Require_once ($this->cacheid);      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. '; }}?>

Demo.php:

<?php/** can be reproduced freely, please keep the copyright information, thank you for using!* class Name:cache (for PHP5) * version:1.0* Description: Dynamic cache class, used to control the page automatically generate cache, call cache, update slow Save, delete cache. * Last modify:2007-8-22* remark:1. This version is PHP5 version, I do not write PHP4 version, if necessary, please refer to the modification (easier, not so lazy, hehe!). 2. This version is UTF-8 encoding, if the website uses other encoding, please convert, Windows system with Notepad open Save As, select the appropriate encoding (general ANSI), under Linux use the appropriate editing software or ICONV command line. 3. Copy and paste the above 2nd. * A little bit about the cache: * The fundamental difference between dynamic and static caches is that they are automatic, and the process of user access to the page is to generate caches, browse caches, and update caches without manual intervention. * Static caching refers to generating static pages,  Related operations are generally done in the background of the site, manual operation (that is, manually generated). *//** Use Method Example *///demo1:require_once (' cache.inc.php '); $cachedir = './cache/'; Set cache Directory $cache = new cache ($cachedir, 10);  The default setting for omitting parameters is $cache = new cache ($CACHEDIR); if ($_get[' cacheact ']! = ' rewrite ')//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 the cache, the cache is valid then do not execute the following page code//page code start echo date (' h:i:s JS F '); Page code end $cache->write ();  First run or cache expiration, generate cache//demo2:require_once (' cache.inc.php '); $cachedir = './cache/'; Set cache Directory $cache = new cache ($cachedir, 10);  The default setting for omitting parameters is $cache = new cache ($CACHEDIR); IF ($_get[' cacheact ']! = ' rewrite ')//Here is a tip, through XX. Php?cacheact=rewrite update the cache, and so on, you can also set some other operations $cache->load ();  Load cache, the cache is valid do not execute the following page code//page code Start $content = Date (' h:i:s JS F ');  Echo $content; Page code End $cache->write (1, $content);  First run or cache expiration, generate cache//demo3:require_once (' cache.inc.php ');  Define (' cacheenable ', true); if (cacheenable) {$cachedir = './cache/';//Set cache directory $cache = new cache ($cachedir, 10);//omit parameter takes default setting, $cache = new Ca    Che ($cachedir); if ($_get[' cacheact ']! = ' rewrite ')//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, the cache is valid do not execute the following page code}//page code Start $content = Date (' h:i:s JS F ');  Echo $content; Page code End if (cacheenable) $cache->write (1, $content); First run or cache expiration, generate cache?>

I hope this article is helpful to everyone's PHP programming.

http://www.bkjia.com/PHPjc/1039189.html www.bkjia.com true http://www.bkjia.com/PHPjc/1039189.html techarticle PHP implementation of the simple cache class, PHP implementation of the cache This article describes the PHP implementation of the simple cache class. Share to everyone for your reference. As follows: Cache.inc.php:phpclass Cache {...

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