You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

101 lines
2.2 KiB

  1. <?php
  2. namespace Kuxin\Cache;
  3. use Kuxin\Config;
  4. use Kuxin\Helper\Serialize;
  5. class File
  6. {
  7. /**
  8. * 缓存路径
  9. *
  10. * @var string
  11. */
  12. public $path = '';
  13. /**
  14. * @var string 缓存前缀
  15. */
  16. protected $prefix = '';
  17. public function __construct($option)
  18. {
  19. $this->path = $option['path'] ?? KX_ROOT . '/storage/cache';
  20. $this->prefix = $option['prefix'] ?? Config::get('cache.prefix', '');
  21. }
  22. public function set(string $key, $value, int $time = 0)
  23. {
  24. $file = $this->key2file($key);
  25. $data['data'] = $value;
  26. $data['time'] = ($time == 0) ? 0 : ($_SERVER['REQUEST_TIME'] + $time);
  27. return file_put_contents($file, Serialize::encode($data));
  28. }
  29. public function get(string $key)
  30. {
  31. $file = $this->key2file($key);
  32. if (is_file($file)) {
  33. $data = Serialize::decode(file_get_contents($file));
  34. if ($data && ($data['time'] > 0 && $data['time'] < $_SERVER['REQUEST_TIME'])) {
  35. $this->remove($key);
  36. return null;
  37. }
  38. return $data['data'];
  39. } else {
  40. return null;
  41. }
  42. }
  43. public function remove(string $key)
  44. {
  45. $file = $this->key2file($key);
  46. if (is_file($file))
  47. return unlink($file);
  48. return false;
  49. }
  50. public function inc(string $key, int $num = 1)
  51. {
  52. $data = $this->get($key);
  53. if ($data) {
  54. $data += $num;
  55. $this->set($key, $data);
  56. return $data;
  57. }
  58. return false;
  59. }
  60. public function dec(string $key, int $num = 1)
  61. {
  62. $data = $this->get($key);
  63. if ($data) {
  64. $data -= $num;
  65. $this->set($key, $data);
  66. return $data;
  67. }
  68. return false;
  69. }
  70. public function clear()
  71. {
  72. }
  73. protected function key2file(string $key)
  74. {
  75. if (is_array($key)) {
  76. $key = Serialize::encode($key);
  77. }
  78. $key = md5($key);
  79. $path = $this->path . '/' . $key{0} . '/' . $key{1} . '/';
  80. if (!is_dir($path)) {
  81. mkdir($path, 0755, true);
  82. }
  83. $file = $path . $key . '.php';
  84. return $file;
  85. }
  86. }