php文件缓存类用法实例分析

这篇文章主要介绍了php文件缓存类用法,以实例形式较为详细的分析了php文件缓存类的定义、功能及具体使用技巧,非常具有实用价值,需要的朋友可以参考下

本文实例讲述了php文件缓存类用法,分享给大家供大家参考,具体如下:

  1. <?php
  2. /**
  3. * 简单的文件缓存类
  4. *
  5. */
  6. class XZCache{
  7. // default cache time one hour
  8. var $cache_time = 3600;
  9. // default cache dir
  10. var $cache_dir = './cache';
  11. public function __construct($cache_dir=null, $cache_time=null){
  12. $this->cache_dir = isset($cache_dir) ? $cache_dir : $this->cache_dir;
  13. $this->cache_time = isset($cache_time) ? $cache_time : $this->cache_time;
  14. }
  15. public function saveCache ($key, $value){
  16. if (is_dir($this->cache_dir)){
  17. $cache_file = $this->cache_dir . '/xzcache_' . md5($key);
  18. $timedif = @(time() - filemtime($cache_file));
  19. if ($timedif >= $this->cache_time) {
  20. // cached file is too old, create new
  21. $serialized = serialize($value);
  22. if ($f = @fopen($cache_file, 'w')) {
  23. fwrite ($f, $serialized, strlen($serialized));
  24. fclose($f);
  25. }
  26. }
  27. $result = 1;
  28. }else{
  29. echo "Error:dir is not exist.";
  30. $result = 0;
  31. }
  32. return $result;
  33. }
  34. /**
  35. * @return array
  36. * 0 no cache
  37. * 1 cached
  38. * 2 overdue
  39. */
  40. public function getCache ($key) {
  41. $cache_file = $this->cache_dir . '/xzcache_' . md5($key);
  42. if (is_dir($this->cache_dir) && is_file($cache_file)) {
  43. $timedif = @(time() - filemtime($cache_file));
  44. if ($timedif >= $this->cache_time) {
  45. $result['cached'] = 2;
  46. }else{
  47. // cached file is fresh enough, return cached array
  48. $result['value'] = unserialize(file_get_contents($cache_file));
  49. $result['cached'] = 1;
  50. }
  51. }else {
  52. echo "Error:no cache";
  53. $result['cached'] = 0;
  54. }
  55. return $result;
  56. }
  57. } //end of class

用法示例如下:

  1. $cache = new XZCache();
  2. $key = 'global';
  3. $value = $GLOBALS;
  4. $cache->saveCache($key, $value);
  5. $result = $cache->getCache($key);
  6. var_dump($result);