Home >Backend Development >PHP Tutorial >A PHP cache class and calling example

A PHP cache class and calling example

WBOY
WBOYOriginal
2016-07-25 08:59:201183browse
  1. class Cache {
  2. /**
  3. * $dir: cache file storage directory
  4. * $lifetime: cache file validity period, in seconds
  5. * $cacheid: cache file path, including file name
  6. * $ext: cache file extension (optional), used here is For the convenience of viewing files
  7. */
  8. private $dir;
  9. private $lifetime;
  10. private $cacheid;
  11. private $ext;
  12. /**
  13. * Destructor, check whether the cache directory is valid, default assignment
  14. */
  15. function __construct($dir='',$lifetime=1800) {
  16. if ($this->dir_isvalid($dir)) {
  17. $this->dir = $dir;
  18. $this->lifetime = $lifetime;
  19. $this->ext = '.Php';
  20. $this->cacheid = $this->getcacheid();
  21. }
  22. }
  23. /**
  24. * Check if the cache is valid
  25. * edit bbs.it-home.org
  26. */
  27. private function isvalid() {
  28. if (!file_exists($this->cacheid)) return false;
  29. if (!(@$mtime = filemtime($this->cacheid))) return false;
  30. if (mktime() - $mtime > $this->lifetime) return false;
  31. return true;
  32. }
  33. /**
  34. * Write to the cache
  35. * $mode == 0, obtain the page content through the browser cache
  36. * $mode == 1, obtain the page content through direct assignment (received through the $content parameter)
  37. * $mode = = 2, get the page content by reading it locally (fopen ile_get_contents) (it seems that this method is unnecessary)
  38. */
  39. public function write($mode=0,$content='') {
  40. switch ($mode) {
  41. case 0:
  42. $content = ob_get_contents();
  43. break;
  44. default:
  45. break;
  46. }
  47. ob_end_flush();
  48. try {
  49. file_put_contents($this->cacheid,$content);
  50. }
  51. catch (Exception $e) {
  52. $this->error('写入缓存失败!请检查目录权限!');
  53. }
  54. }
  55. /**
  56. * Load the cache
  57. * exit() After loading the cache, terminate the execution of the original page program. If the cache is invalid, run the original page program to generate a cache
  58. * ob_start() Enable the browser cache to obtain the page content at the end of the page
  59. */
  60. public function load() {
  61. if ($this->isvalid()) {
  62. echo "This is Cache. ";
  63. //以下两种方式,哪种方式好?????
  64. require_once($this->cacheid);
  65. //echo file_get_contents($this->cacheid);
  66. exit();
  67. }
  68. else {
  69. ob_start();
  70. }
  71. }
  72. /**
  73. * Clear cache
  74. */
  75. public function clean() {
  76. try {
  77. unlink($this->cacheid);
  78. }
  79. catch (Exception $e) {
  80. $this->error('清除缓存文件失败!请检查目录权限!');
  81. }
  82. }
  83. /**
  84. * Get cache file path
  85. */
  86. private function getcacheid() {
  87. return $this->dir.md5($this->geturl()).$this->ext;
  88. }
  89. /**
  90. * Check if the directory exists or can be created
  91. */
  92. private function dir_isvalid($dir) {
  93. if (is_dir($dir)) return true;
  94. try {
  95. mkdir($dir,0777);
  96. }
  97. catch (Exception $e) {
  98. $this->error('所设定缓存目录不存在并且创建失败!请检查目录权限!');
  99. return false;
  100. }
  101. return true;
  102. }
  103. /**
  104. * Get the complete url of the current page
  105. */
  106. private function geturl() {
  107. $url = '';
  108. if (isset($_SERVER['REQUEST_URI'])) {
  109. $url = $_SERVER['REQUEST_URI'];
  110. }
  111. else {
  112. $url = $_SERVER['Php_SELF'];
  113. $url .= empty($_SERVER['QUERY_STRING'])?'':'?'.$_SERVER['QUERY_STRING'];
  114. }
  115. return $url;
  116. }
  117. /**
  118. * Output error message
  119. */
  120. private function error($str) {
  121. echo '
    '.$str.'
    ';
  122. }
  123. }
  124. ?>
复制代码

2. Demonstration code of php cache class

  1. /*

  2. * Can be freely reproduced and used, please retain the copyright information, thank you for using!
  3. * Class Name: Cache (For Php5)
  4. * Version: 1.0
  5. * Description: Dynamic cache class, used to control the page to automatically generate cache, call cache, update cache, delete cache.
  6. * Remark:
  7. 1. This version is Php5 version
  8. 2. This version is utf-8 encoding, if the website uses other Please convert the encoding yourself. For Windows systems, use Notepad to open and save as, and select the corresponding encoding (generally ANSI). For Linux, please use the corresponding editing software or the iconv command line.
  9. 3. If you copy and paste, ignore item 2 above. .
  10. * Some thoughts about caching:
  11. * The fundamental difference between dynamic caching and static caching is that it is automatic. The process of user accessing a page is the process of generating cache, browsing cache, and updating cache, without manual intervention.
  12. * Static caching It refers to generating static pages. The related operations are usually completed in the background of the website and require manual operation (that is, manual generation).
  13. */
  14. /*
  15. * Examples of usage
  16. ----------Demo1 --------
  17. require_once('cache.inc.php');
  18. $cachedir = './Cache/'; //Set the cache directory
  19. $cache = new Cache($cachedir,10); //Omit the parameters and use the default settings, $cache = new Cache($cachedir);
  20. if ($_GET['cacheact'] != 'rewrite') //Here is a trick, through xx.Php?cacheact =rewrite updates the cache
  21. $cache->load(); //Load the cache. If the cache is valid, the following page code will not be executed
  22. //The page code starts
  23. echo date('H:i:s jS F');
  24. / /End of page code
  25. $cache->write(); //First run or cache expiration, generate cache

  26. ---------Demo2------ -

  27. require_once('cache.inc.php');
  28. $cachedir = './Cache/'; //Set the cache directory
  29. $cache = new Cache($cachedir,10); //Omit the parameter and use the default Provincial settings, $cache = new Cache($cachedir);
  30. if ($_GET['cacheact'] != 'rewrite') //Here is a trick, update the cache through xx.Php?cacheact=rewrite
  31. $cache ->load(); //Load the cache. If the cache is valid, the following page code will not be executed
  32. //The page code starts
  33. $content = date('H:i:s jS F');
  34. echo $content;
  35. / /End of page code
  36. $cache->write(1,$content); //First run or cache expiration, generate cache

  37. ------------- Demo3----

  38. require_once('cache.inc.php');
  39. define('CACHEENABLE',true);
  40. if (CACHEENABLE) {
  41. $cachedir = './Cache/'; //Set cache Directory
  42. $cache = new Cache($cachedir,10); //Omit the parameters to adopt the default settings, $cache = new Cache($cachedir);
  43. if ($_GET['cacheact'] != 'rewrite') //Here is a trick, update the cache through xx.Php?cacheact=rewrite
  44. $cache->load(); //Load the cache, if the cache is valid, the following page code will not be executed
  45. }
  46. //The page code starts
  47. $content = date('H:i:s jS F');
  48. echo $content;
  49. //End of page code
  50. if (CACHEENABLE)
  51. $cache->write(1,$content); //First run Or the cache expires, generate cache
  52. */
  53. ?>

Copy code


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn