Simple and Practical PHP Text Cache Class Instance

  • 2021-12-04 18:24:58
  • OfStack

Cache is widely used in practical use, which can reduce the access to 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, which can refer to the cache mechanism and writing method.

cache.inc.php


<?php
class Cache {
 /**
 * $dir :  Cache file storage directory 
 * $lifetime :  Validity period of cache file , In seconds 
 * $cacheid :  Cache file path , Include file name 
 * $ext :  Cache file extension ( You can not use it ), It is used here for the 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 the page content in the form of browser cache 
 * $mode == 1 ,  To assign a value directly ( Pass $content Parameter reception ) Get the page content in the way of 
 * $mode == 2 ,  Read locally (fopen ile_get_contents) Get the page content in the way of ( 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(' Failed to write to cache ! Please check directory permissions !');
  }
 }
 /**
 *  Load cache 
 * exit()  Terminate the execution of the original page program after loading the cache , If the cache is invalid, run the original page program to generate the cache 
 * ob_start()  Turn on browser cache to get the page content at the end of the page 
 */
 public function load() {
  if ($this->isvalid()) {
   echo "This is Cache. ";
   // The following two ways , Which way is better ?????
   require_once($this->cacheid);
   //echo file_get_contents($this->cacheid);
   exit();
  }
  else {
   ob_start();
  }
 }
 /**
 *  Clear the cache 
 */
 public function clean() {
  try {
   unlink($this->cacheid);
  }
  catch (Exception $e) {
   $this->error(' Failed to clear cache file ! Please check directory permissions !');
  }
 }
 /**
 *  Get the 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 failed to create ! Please check directory permissions !');
    return false;   
  }
  return true;
 }
 /**
 *  Get the current page complete 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
/*
 *  Examples of usage 
 */
 ------------------------------------Demo1-------------------------------------------
 require_once('cache.inc.php');
 $cachedir = './Cache/'; // Set the cache directory 
 $cache = new Cache($cachedir,10); // Omit the parameter to take the default setting , $cache = new Cache($cachedir);
 if ($_GET['cacheact'] != 'rewrite') // Here is 1 Skill , Pass xx.Php?cacheact=rewrite Update cache , And so on , You can also set 1 Some other operations 
  $cache->load(); // Load 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(); // First run or cache expiration , Generate cache 
 ------------------------------------Demo2-------------------------------------------
 require_once('cache.inc.php');
 $cachedir = './Cache/'; // Set the cache directory 
 $cache = new Cache($cachedir,10); // Omit the parameter to take the default setting , $cache = new Cache($cachedir);
 if ($_GET['cacheact'] != 'rewrite') // Here is 1 Skill , Pass xx.Php?cacheact=rewrite Update cache , And so on , You can also set 1 Some other operations 
  $cache->load(); // Load 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); // First run or cache expiration , Generate cache 
 ------------------------------------Demo3-------------------------------------------
 require_once('cache.inc.php');
 define('CACHEENABLE',true);
 if (CACHEENABLE) {
  $cachedir = './Cache/'; // Set the cache directory 
  $cache = new Cache($cachedir,10); // Omit the parameter to take the default setting , $cache = new Cache($cachedir);
  if ($_GET['cacheact'] != 'rewrite') // Here is 1 Skill , Pass xx.Php?cacheact=rewrite Update cache , And so on , You can also set 1 Some other operations 
   $cache->load(); // Load 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); // First run or cache expiration , Generate cache 
?>

Summarize


Related articles: