FileCache.php 10 KB

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