cache_class.php 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112
  1. <?php
  2. /**
  3. * @copyright (c) 2011 aircheng.com
  4. * @file cache.php
  5. * @brief 缓存类
  6. * @author chendeshan
  7. * @date 2011-7-8 16:02:31
  8. * @version 0.6
  9. */
  10. /**
  11. * @brief 缓存类
  12. * @class ICache
  13. */
  14. class ICache
  15. {
  16. private $cache = null; //缓存对象
  17. private $cacheType = 'file'; //默认缓存类型
  18. private $expire = 2592000; //默认缓存过期时间,单位:秒,默认:1个月
  19. private $timeout = 0; //默认缓存删除延迟时间,单位:秒
  20. /**
  21. * @brief 根据缓存类型创建缓存对象
  22. * @param string $cacheType 缓存类型值
  23. */
  24. public function __construct($cacheType = '')
  25. {
  26. $this->cacheType = $cacheType ? $cacheType : $this->cacheType;
  27. $this->expire = isset(IWeb::$app->config['cache']['expire']) ? IWeb::$app->config['cache']['expire'] : $this->expire;
  28. $this->timeout = isset(IWeb::$app->config['cache']['timeout']) ? IWeb::$app->config['cache']['timeout'] : $this->timeout;
  29. //当前系统支持的缓存类型
  30. switch($this->cacheType)
  31. {
  32. case "memcache":
  33. $this->cache = new IMemCache();
  34. break;
  35. default:
  36. $this->cache = new IFileCache();
  37. break;
  38. }
  39. }
  40. /**
  41. * @brief 写入缓存
  42. * @param string $key 缓存的唯一key值
  43. * @param mixed $data 要写入的缓存数据
  44. * @param int $expire 缓存数据失效时间,单位:秒
  45. * @return bool true:成功;false:失败;
  46. */
  47. public function set($key,$data,$expire = '')
  48. {
  49. if($expire === '')
  50. {
  51. $expire = $this->expire;
  52. }
  53. $data = serialize($data);
  54. return $this->cache->set($key,$data,$expire);
  55. }
  56. /**
  57. * @brief 读取缓存
  58. * @param string $key 缓存的唯一key值,当要返回多个值时可以写成数组
  59. * @return mixed 读取出的缓存数据;null:没有取到数据;
  60. */
  61. public function get($key)
  62. {
  63. $data = $this->cache->get($key);
  64. if($data)
  65. {
  66. return unserialize($data);
  67. }
  68. else
  69. {
  70. return null;
  71. }
  72. }
  73. /**
  74. * @brief 删除缓存
  75. * @param string $key 缓存的唯一key值
  76. * @param int $timeout 在间隔单位时间内自动删除,单位:秒
  77. * @return bool true:成功; false:失败;
  78. */
  79. public function del($key,$timeout = '')
  80. {
  81. if($timeout === '')
  82. {
  83. $timeout = $this->timeout;
  84. }
  85. return $this->cache->del($key,$timeout);
  86. }
  87. /**
  88. * @brief 删除全部缓存
  89. * @return bool true:成功;false:失败;
  90. */
  91. public function flush()
  92. {
  93. return $this->cache->flush();
  94. }
  95. /**
  96. * @brief 获取缓存类型
  97. * @return string 缓存类型
  98. */
  99. public function getCacheType()
  100. {
  101. return $this->cacheType;
  102. }
  103. }