StoreFile.php 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125
  1. <?php
  2. class LtStoreFile implements LtStore
  3. {
  4. public $storeDir;
  5. public $prefix = 'LtStore';
  6. public $useSerialize = false;
  7. static public $defaultStoreDir = "/tmp/LtStoreFile/";
  8. public function init()
  9. {
  10. /**
  11. * 目录不存在和是否可写在调用add是测试
  12. * @todo detect dir is exists and writable
  13. */
  14. if (null == $this->storeDir)
  15. {
  16. $this->storeDir = self::$defaultStoreDir;
  17. }
  18. $this->storeDir = str_replace('\\', '/', $this->storeDir);
  19. $this->storeDir = rtrim($this->storeDir, '\\/') . '/';
  20. }
  21. /**
  22. * 当key存在时:
  23. * 如果没有过期, 不更新值, 返回 false
  24. * 如果已经过期, 更新值, 返回 true
  25. *
  26. * @return bool
  27. */
  28. public function add($key, $value)
  29. {
  30. $file = $this->getFilePath($key);
  31. $cachePath = pathinfo($file, PATHINFO_DIRNAME);
  32. if (!is_dir($cachePath))
  33. {
  34. if (!@mkdir($cachePath, 0777, true))
  35. {
  36. trigger_error("Can not create $cachePath");
  37. }
  38. }
  39. if (is_file($file))
  40. {
  41. return false;
  42. }
  43. if ($this->useSerialize)
  44. {
  45. $value = serialize($value);
  46. }
  47. $length = file_put_contents($file, '<?php exit;?>' . $value);
  48. return $length > 0 ? true : false;
  49. }
  50. /**
  51. * 删除不存在的key返回false
  52. *
  53. * @return bool
  54. */
  55. public function del($key)
  56. {
  57. $file = $this->getFilePath($key);
  58. if (!is_file($file))
  59. {
  60. return false;
  61. }
  62. else
  63. {
  64. return @unlink($file);
  65. }
  66. }
  67. /**
  68. * 取不存在的key返回false
  69. * 已经过期返回false
  70. *
  71. * @return 成功返回数据,失败返回false
  72. */
  73. public function get($key)
  74. {
  75. $file = $this->getFilePath($key);
  76. if (!is_file($file))
  77. {
  78. return false;
  79. }
  80. $str = file_get_contents($file);
  81. $value = substr($str, 13);
  82. if ($this->useSerialize)
  83. {
  84. $value = unserialize($value);
  85. }
  86. return $value;
  87. }
  88. /**
  89. * key不存在 返回false
  90. * 不管有没有过期,都更新数据
  91. *
  92. * @return bool
  93. */
  94. public function update($key, $value)
  95. {
  96. $file = $this->getFilePath($key);
  97. if (!is_file($file))
  98. {
  99. return false;
  100. }
  101. else
  102. {
  103. if ($this->useSerialize)
  104. {
  105. $value = serialize($value);
  106. }
  107. $length = file_put_contents($file, '<?php exit;?>' . $value);
  108. return $length > 0 ? true : false;
  109. }
  110. }
  111. public function getFilePath($key)
  112. {
  113. $token = md5($key);
  114. return $this->storeDir .
  115. $this->prefix . '/' .
  116. substr($token, 0, 2) .'/' .
  117. substr($token, 2, 2) . '/' .
  118. $token . '.php';
  119. }
  120. }