FileCache.php 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. <?php
  2. /**
  3. * FileCache 文件缓存
  4. *
  5. * @author gaoming13 <gaoming13@yeah.net>
  6. * @link https://github.com/gaoming13/wechat-php-sdk
  7. * @link http://me.diary8.com/
  8. */
  9. namespace echowx\utils;
  10. class FileCache {
  11. protected $options = [
  12. 'expire' => 7000,
  13. 'cache_subdir' => true,
  14. 'prefix' => '',
  15. 'path' => CACHE_PATH,
  16. 'data_compress' => false,
  17. ];
  18. /**
  19. * 构造函数
  20. * @param array $options
  21. */
  22. public function __construct($options = [])
  23. {
  24. if (!empty($options)) {
  25. $this->options = array_merge($this->options, $options);
  26. }
  27. if (substr($this->options['path'], -1) != '/') {
  28. $this->options['path'] .= '/';
  29. }
  30. $this->init();
  31. }
  32. /**
  33. * 初始化检查
  34. * @access private
  35. * @return boolean
  36. */
  37. private function init()
  38. {
  39. // 创建项目缓存目录
  40. if (!is_dir($this->options['path'])) {
  41. if (mkdir($this->options['path'], 0755, true)) {
  42. return true;
  43. }
  44. }
  45. return false;
  46. }
  47. public function get($name, $default = false)
  48. {
  49. $filename = $this->getCacheKey($name);
  50. if (!is_file($filename)) {
  51. return $default;
  52. }
  53. $content = file_get_contents($filename);
  54. if (false !== $content) {
  55. $arr = json_decode($content,true);
  56. if($arr['expire'] <= time())
  57. {
  58. return false;
  59. }
  60. return $content;
  61. }
  62. }
  63. public function set($name, $value, $expire = null)
  64. {
  65. if (is_null($expire)) {
  66. $expire = $this->options['expire'];
  67. }
  68. $filename = $this->getCacheKey($name);
  69. $json = json_encode(array($name=>$value,"expire"=>time()+$expire));
  70. $result = file_put_contents($filename,$json);
  71. if ($result) {
  72. return true;
  73. }
  74. return false;
  75. }
  76. /**
  77. * 获取缓存文件名
  78. * @dateTime 2018-01-29T14:32:49+0800
  79. * @author xm
  80. * @return [type] [description]
  81. */
  82. public function getCacheKey($name)
  83. {
  84. return $this->options['path']."/".$name.'_cache.php';
  85. }
  86. }