php 缓存类的简单示例

前端之家收集整理的这篇文章主要介绍了php 缓存类的简单示例前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
对一个简单的PHP缓存类感兴趣的小伙伴,下面一起跟随编程之家 jb51.cc的小编两巴掌来看看吧!
  1. <?PHP
  2. /**
  3. * 一个简单的PHP缓存类
  4. *
  5. * @param
  6. * @author 网: jb51.cc
  7. * Class Cache
  8. * @author Koen Ekelschot
  9. * @license WTFPL
  10. */
  11. class Cache {
  12. private $cachedFile;
  13. public function __construct($identifier) {
  14. $this->cachedFile = ROOT.DS.'tmp'.DS.'cache'.DS.md5($identifier);
  15. }
  16. public function cacheExists($maxAge) {
  17. if (file_exists($this->cachedFile) && !is_dir($this->cachedFile)) {
  18. if (filemtime($this->cachedFile) + $maxAge > time()) {
  19. return true;
  20. } else {
  21. $this->invalidateCache();
  22. }
  23. }
  24. return false;
  25. }
  26. public function getCachedCopy() {
  27. $contents = file_get_contents($this->cachedFile);
  28. return unserialize(base64_decode($contents));
  29. }
  30. public function getCachedFilename() {
  31. return str_replace(ROOT,'',$this->cachedFile);
  32. }
  33. public function cacheResult($result) {
  34. if (file_exists($this->cachedFile) && !is_dir($this->cachedFile)) {
  35. $this->invalidateCache();
  36. }
  37. $base64 = base64_encode(serialize($result));
  38. file_put_contents($this->cachedFile,$base64);
  39. }
  40. private function invalidateCache() {
  41. unlink($this->cachedFile);
  42. }
  43. }
  44. /*** 来自编程之家 jb51.cc(jb51.cc) ***/

猜你在找的PHP相关文章