Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

FileCache.php 10KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269
  1. <?php
  2. /**
  3. * @link http://www.yiiframework.com/
  4. * @copyright Copyright (c) 2008 Yii Software LLC
  5. * @license http://www.yiiframework.com/license/
  6. */
  7. namespace yii\caching;
  8. use Yii;
  9. use yii\helpers\FileHelper;
  10. /**
  11. * FileCache implements a cache component using files.
  12. *
  13. * For each data value being cached, FileCache will store it in a separate file.
  14. * The cache files are placed under [[cachePath]]. FileCache will perform garbage collection
  15. * automatically to remove expired cache files.
  16. *
  17. * Please refer to [[Cache]] for common cache operations that are supported by FileCache.
  18. *
  19. * @author Qiang Xue <qiang.xue@gmail.com>
  20. * @since 2.0
  21. */
  22. class FileCache extends Cache
  23. {
  24. /**
  25. * @var string a string prefixed to every cache key. This is needed when you store
  26. * cache data under the same [[cachePath]] for different applications to avoid
  27. * conflict.
  28. *
  29. * To ensure interoperability, only alphanumeric characters should be used.
  30. */
  31. public $keyPrefix = '';
  32. /**
  33. * @var string the directory to store cache files. You may use path alias here.
  34. * If not set, it will use the "cache" subdirectory under the application runtime path.
  35. */
  36. public $cachePath = '@runtime/cache';
  37. /**
  38. * @var string cache file suffix. Defaults to '.bin'.
  39. */
  40. public $cacheFileSuffix = '.bin';
  41. /**
  42. * @var integer the level of sub-directories to store cache files. Defaults to 1.
  43. * If the system has huge number of cache files (e.g. one million), you may use a bigger value
  44. * (usually no bigger than 3). Using sub-directories is mainly to ensure the file system
  45. * is not over burdened with a single directory having too many files.
  46. */
  47. public $directoryLevel = 1;
  48. /**
  49. * @var integer the probability (parts per million) that garbage collection (GC) should be performed
  50. * when storing a piece of data in the cache. Defaults to 10, meaning 0.001% chance.
  51. * This number should be between 0 and 1000000. A value 0 means no GC will be performed at all.
  52. */
  53. public $gcProbability = 10;
  54. /**
  55. * @var integer the permission to be set for newly created cache files.
  56. * This value will be used by PHP chmod() function. No umask will be applied.
  57. * If not set, the permission will be determined by the current environment.
  58. */
  59. public $fileMode;
  60. /**
  61. * @var integer the permission to be set for newly created directories.
  62. * This value will be used by PHP chmod() function. No umask will be applied.
  63. * Defaults to 0775, meaning the directory is read-writable by owner and group,
  64. * but read-only for other users.
  65. */
  66. public $dirMode = 0775;
  67. /**
  68. * Initializes this component by ensuring the existence of the cache path.
  69. */
  70. public function init()
  71. {
  72. parent::init();
  73. $this->cachePath = Yii::getAlias($this->cachePath);
  74. if (!is_dir($this->cachePath)) {
  75. FileHelper::createDirectory($this->cachePath, $this->dirMode, true);
  76. }
  77. }
  78. /**
  79. * Checks whether a specified key exists in the cache.
  80. * This can be faster than getting the value from the cache if the data is big.
  81. * Note that this method does not check whether the dependency associated
  82. * with the cached data, if there is any, has changed. So a call to [[get]]
  83. * may return false while exists returns true.
  84. * @param mixed $key a key identifying the cached value. This can be a simple string or
  85. * a complex data structure consisting of factors representing the key.
  86. * @return boolean true if a value exists in cache, false if the value is not in the cache or expired.
  87. */
  88. public function exists($key)
  89. {
  90. $cacheFile = $this->getCacheFile($this->buildKey($key));
  91. return @filemtime($cacheFile) > time();
  92. }
  93. /**
  94. * Retrieves a value from cache with a specified key.
  95. * This is the implementation of the method declared in the parent class.
  96. * @param string $key a unique key identifying the cached value
  97. * @return string|boolean the value stored in cache, false if the value is not in the cache or expired.
  98. */
  99. protected function getValue($key)
  100. {
  101. $cacheFile = $this->getCacheFile($key);
  102. if (@filemtime($cacheFile) > time()) {
  103. $fp = @fopen($cacheFile, 'r');
  104. if ($fp !== false) {
  105. @flock($fp, LOCK_SH);
  106. $cacheValue = @stream_get_contents($fp);
  107. @flock($fp, LOCK_UN);
  108. @fclose($fp);
  109. return $cacheValue;
  110. }
  111. }
  112. return false;
  113. }
  114. /**
  115. * Stores a value identified by a key in cache.
  116. * This is the implementation of the method declared in the parent class.
  117. *
  118. * @param string $key the key identifying the value to be cached
  119. * @param string $value the value to be cached
  120. * @param integer $duration the number of seconds in which the cached value will expire. 0 means never expire.
  121. * @return boolean true if the value is successfully stored into cache, false otherwise
  122. */
  123. protected function setValue($key, $value, $duration)
  124. {
  125. $this->gc();
  126. $cacheFile = $this->getCacheFile($key);
  127. if ($this->directoryLevel > 0) {
  128. @FileHelper::createDirectory(dirname($cacheFile), $this->dirMode, true);
  129. }
  130. if (@file_put_contents($cacheFile, $value, LOCK_EX) !== false) {
  131. if ($this->fileMode !== null) {
  132. @chmod($cacheFile, $this->fileMode);
  133. }
  134. if ($duration <= 0) {
  135. $duration = 31536000; // 1 year
  136. }
  137. return @touch($cacheFile, $duration + time());
  138. } else {
  139. $error = error_get_last();
  140. Yii::warning("Unable to write cache file '{$cacheFile}': {$error['message']}", __METHOD__);
  141. return false;
  142. }
  143. }
  144. /**
  145. * Stores a value identified by a key into cache if the cache does not contain this key.
  146. * This is the implementation of the method declared in the parent class.
  147. *
  148. * @param string $key the key identifying the value to be cached
  149. * @param string $value the value to be cached
  150. * @param integer $duration the number of seconds in which the cached value will expire. 0 means never expire.
  151. * @return boolean true if the value is successfully stored into cache, false otherwise
  152. */
  153. protected function addValue($key, $value, $duration)
  154. {
  155. $cacheFile = $this->getCacheFile($key);
  156. if (@filemtime($cacheFile) > time()) {
  157. return false;
  158. }
  159. return $this->setValue($key, $value, $duration);
  160. }
  161. /**
  162. * Deletes a value with the specified key from cache
  163. * This is the implementation of the method declared in the parent class.
  164. * @param string $key the key of the value to be deleted
  165. * @return boolean if no error happens during deletion
  166. */
  167. protected function deleteValue($key)
  168. {
  169. $cacheFile = $this->getCacheFile($key);
  170. return @unlink($cacheFile);
  171. }
  172. /**
  173. * Returns the cache file path given the cache key.
  174. * @param string $key cache key
  175. * @return string the cache file path
  176. */
  177. protected function getCacheFile($key)
  178. {
  179. if ($this->directoryLevel > 0) {
  180. $base = $this->cachePath;
  181. for ($i = 0; $i < $this->directoryLevel; ++$i) {
  182. if (($prefix = substr($key, $i + $i, 2)) !== false) {
  183. $base .= DIRECTORY_SEPARATOR . $prefix;
  184. }
  185. }
  186. return $base . DIRECTORY_SEPARATOR . $key . $this->cacheFileSuffix;
  187. } else {
  188. return $this->cachePath . DIRECTORY_SEPARATOR . $key . $this->cacheFileSuffix;
  189. }
  190. }
  191. /**
  192. * Deletes all values from cache.
  193. * This is the implementation of the method declared in the parent class.
  194. * @return boolean whether the flush operation was successful.
  195. */
  196. protected function flushValues()
  197. {
  198. $this->gc(true, false);
  199. return true;
  200. }
  201. /**
  202. * Removes expired cache files.
  203. * @param boolean $force whether to enforce the garbage collection regardless of [[gcProbability]].
  204. * Defaults to false, meaning the actual deletion happens with the probability as specified by [[gcProbability]].
  205. * @param boolean $expiredOnly whether to removed expired cache files only.
  206. * If false, all cache files under [[cachePath]] will be removed.
  207. */
  208. public function gc($force = false, $expiredOnly = true)
  209. {
  210. if ($force || mt_rand(0, 1000000) < $this->gcProbability) {
  211. $this->gcRecursive($this->cachePath, $expiredOnly);
  212. }
  213. }
  214. /**
  215. * Recursively removing expired cache files under a directory.
  216. * This method is mainly used by [[gc()]].
  217. * @param string $path the directory under which expired cache files are removed.
  218. * @param boolean $expiredOnly whether to only remove expired cache files. If false, all files
  219. * under `$path` will be removed.
  220. */
  221. protected function gcRecursive($path, $expiredOnly)
  222. {
  223. if (($handle = opendir($path)) !== false) {
  224. while (($file = readdir($handle)) !== false) {
  225. if ($file[0] === '.') {
  226. continue;
  227. }
  228. $fullPath = $path . DIRECTORY_SEPARATOR . $file;
  229. if (is_dir($fullPath)) {
  230. $this->gcRecursive($fullPath, $expiredOnly);
  231. if (!$expiredOnly) {
  232. if (!@rmdir($fullPath)) {
  233. $error = error_get_last();
  234. Yii::warning("Unable to remove directory '{$fullPath}': {$error['message']}", __METHOD__);
  235. }
  236. }
  237. } elseif (!$expiredOnly || $expiredOnly && @filemtime($fullPath) < time()) {
  238. if (!@unlink($fullPath)) {
  239. $error = error_get_last();
  240. Yii::warning("Unable to remove file '{$fullPath}': {$error['message']}", __METHOD__);
  241. }
  242. }
  243. }
  244. closedir($handle);
  245. }
  246. }
  247. }