Home > Backend Development > PHP Tutorial > A PHP caching class

A PHP caching class

WBOY
Release: 2016-07-25 08:45:08
Original
784 people have browsed it
  1. cache.inc.php:
  2. class Cache {
  3. /**
  4. * $dir: cache file storage directory
  5. * $lifetime: cache file validity period, in seconds
  6. * $cacheid: cache file path, including file name
  7. * $ext: cache file extension (optional), used here is For the convenience of viewing files
  8. */
  9. private $dir;
  10. private $lifetime;
  11. private $cacheid;
  12. private $ext;
  13. /**
  14. * Destructor, check whether the cache directory is valid, default assignment
  15. */
  16. function __construct($dir='',$lifetime=1800) {
  17. if ($this->dir_isvalid($dir)) {
  18. $this->dir = $dir;
  19. $this->lifetime = $lifetime;
  20. $this->ext = '.Php';
  21. $this->cacheid = $this->getcacheid();
  22. }
  23. }
  24. /**
  25. * Check if the cache is valid
  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() terminates the execution of the original page program after loading the cache. If the cache is invalid, run the original page program to generate a cache
  58. * ob_start() turns on 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. ?>
复制代码

  1. demo.php:
  2. /*
  3. * Can be freely reproduced and used, please retain the copyright information, thank you for using!
  4. * Class Name: Cache (For Php5)
  5. * Version: 1.0
  6. * Description: Dynamic cache class, used to control the page to automatically generate cache, call cache, update cache, delete cache.
  7. * Author: jiangjun8528@163.com,Junin
  8. * Author Page: http://blog.csdn.Net/sdts /
  9. * Last Modify : 2007-8-22
  10. * Remark :
  11. 1. This version is Php5. I have not written a Php4 version yet. Please refer to the modifications if necessary (it’s easier, don’t be so lazy, haha! ).
  12. 2. This version is encoded in utf-8. If the website uses other encodings, please convert it yourself. On Windows systems, use Notepad to open and save as, and select the corresponding encoding (generally ANSI). Under Linux, please use the corresponding editing software or iconv Command line.
  13. 3. If you copy and paste, ignore the 2nd item above.
  14. * Some thoughts about caching:
  15. * The fundamental difference between dynamic caching and static caching is that it is automatic. The process of user accessing the page is to generate cache. The process of browsing cache and updating cache does not require manual intervention.
  16. * Static caching refers to generating static pages. Related operations are generally completed in the background of the website and require manual operation (that is, manual generation).
  17. */
  18. /*
  19. * Usage examples
  20. ------------------------------------------------Demo1------- ------------------------------------
  21. require_once('cache.inc.php');
  22. $cachedir = './Cache/'; //Set the cache directory
  23. $cache = new Cache($cachedir,10); //Omit the parameters and use the default settings, $cache = new Cache($cachedir);
  24. if ($_GET['cacheact'] != 'rewrite') //Here is a trick, update the cache through xx.Php?cacheact=rewrite, and so on, you can also set some other operations
  25. $cache-> ;load(); //Load the cache. If the cache is valid, the following page code will not be executed
  26. //The page code begins
  27. echo date('H:i:s jS F');
  28. //The page code ends
  29. $cache-> ;write(); //First run or cache expires, generate cache
  30. --------------------------------- ---Demo2-------------------------------------------------
  31. require_once ('cache.inc.php');
  32. $cachedir = './Cache/'; //Set the cache directory
  33. $cache = new Cache($cachedir,10); //Omit the parameters and use the default settings. $cache = new Cache($cachedir);
  34. if ($_GET['cacheact'] != 'rewrite') //Here is a trick, update the cache through xx.Php?cacheact=rewrite, and so on. You can set some other operations
  35. $cache->load(); //Load the cache. If the cache is valid, the following page code will not be executed
  36. //The page code starts
  37. $content = date('H:i:s jS F' );
  38. echo $content;
  39. //End of page code
  40. $cache->write(1,$content); //First run or cache expiration, generate cache
  41. ----------- --------------------------Demo3------------------------ -------------------
  42. require_once('cache.inc.php');
  43. define('CACHEENABLE',true);
  44. if (CACHEENABLE) {
  45. $cachedir = './Cache/'; //Set the cache directory
  46. $cache = new Cache($cachedir,10); //Omit the parameters and use the default settings, $cache = new Cache($cachedir);
  47. if ($_GET['cacheact'] != 'rewrite') //Here is a trick, update the cache through xx.Php?cacheact=rewrite, and so on, you can also set some other operations
  48. $cache-> ;load(); //Load the cache. If the cache is valid, the following page code will not be executed
  49. }
  50. //The page code starts
  51. $content = date('H:i:s jS F');
  52. echo $content;
  53. / /End of page code
  54. if (CACHEENABLE)
  55. $cache->write(1,$content); //First run or cache expiration, generate cache
  56. */
  57. ?>
Copy code

PHP


Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template