A simple and practical example of PHP text cache class

Time:2020-6-25

Cache is widely used in practice, which can reduce the access to the server database and improve the running speed. At present, many CMS content management systems frequently use caching mechanism to improve the efficiency of system operation. The following is a well written cache class. You can refer to the cache mechanism and writing method.

cache.inc.php

<?php
class Cache {
 /**
 *$dir: cache file storage directory
 *$lifetime: cache file validity, in seconds
 *$cacheid: cache file path, including file name
 *$ext: cache file extension (can not be used), which is used here for convenience of viewing files
 */
 private $dir;
 private $lifetime;
 private $cacheid;
 private $ext;
 /**
 *Destructor, check whether 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 whether 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 by browser caching
 *$mode = = 1, get page content by direct assignment (received by $content parameter)
 *$mode = = 2, read locally (fopen ile_ get_ Content) to get the page content (it seems that this way is 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 permission! ');
  }
 }
 /**
 *Load cache
 *Exit() stops the execution of the original pager after loading the cache. If the cache is invalid, the original pager will be run to generate the cache
 * ob_ Start() enables browser caching to get page content at the end of the page
 */
 public function load() {
  if ($this->isvalid()) {
   echo "This is Cache. ";
   //Which of the following two ways is better?????
   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 ('failed to clear cache file! Please check directory permission! ');
  }
 }
 /**
 *Get cache file path
 */
 private function getcacheid() {
  return $this->dir.md5($this->geturl()).$this->ext;
 }
 /**
 *Check 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 ('the set cache directory does not exist and creation failed! Please check the directory permission! ');
    return false;   
  }
  return true;
 }
 /**
 *Get the full URL of the current page
 */
 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
/*
 *Examples of usage
 */
 ------------------------------------Demo1-------------------------------------------
 require_once('cache.inc.php');
 $cachedir = '. / cache /'; // set cache directory
 $cache = new cache ($cachedir, 10); // if you omit the parameter, the default setting is used, $cache = new cache ($cachedir);
 if ($_ Get ['cacheact ']! ='rewrite') // this is a technique. Use xx.Php?cacheact=rewrite Update the cache, and so on. You can also set some other operations
  $cache - > load(); // load the cache. If the cache is valid, the following page code will not be executed
 //Page code start
 echo date('H:i:s jS F');
 //End of page code
 $cache - > write(); // generate the cache after the first run or the cache expires
 ------------------------------------Demo2-------------------------------------------
 require_once('cache.inc.php');
 $cachedir = '. / cache /'; // set cache directory
 $cache = new cache ($cachedir, 10); // if you omit the parameter, the default setting is used, $cache = new cache ($cachedir);
 if ($_ Get ['cacheact ']! ='rewrite') // this is a technique. Use xx.Php?cacheact=rewrite Update the cache, and so on. You can also set some other operations
  $cache - > load(); // load the cache. If the cache is valid, the following page code will not be executed
 //Page code start
 $content = date('H:i:s jS F');
 echo $content;
 //End of page code
 $cache - > write (1, $content); // generate the cache after the first run or the cache expires
 ------------------------------------Demo3-------------------------------------------
 require_once('cache.inc.php');
 define('CACHEENABLE',true);
 if (CACHEENABLE) {
  $cachedir = '. / cache /'; // set cache directory
  $cache = new cache ($cachedir, 10); // if you omit the parameter, the default setting is used, $cache = new cache ($cachedir);
  if ($_ Get ['cacheact ']! ='rewrite') // this is a technique. Use xx.Php?cacheact=rewrite Update the cache, and so on. You can also set some other operations
   $cache - > load(); // load the cache. If the cache is valid, the following page code will not be executed 
 }
 //Page code start
 $content = date('H:i:s jS F');
 echo $content;
 //End of page code
 if (CACHEENABLE)
  $cache - > write (1, $content); // generate the cache after the first run or the cache expires
?>

summary

The above is the whole content of this article. I hope that the content of this article has some reference learning value for your study or work. Thank you for your support for developepaer. If you want to know more about it, please check the relevant links below