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.

FileCache.php 9.7KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258
  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. return @file_get_contents($cacheFile);
  104. } else {
  105. return false;
  106. }
  107. }
  108. /**
  109. * Stores a value identified by a key in cache.
  110. * This is the implementation of the method declared in the parent class.
  111. *
  112. * @param string $key the key identifying the value to be cached
  113. * @param string $value the value to be cached
  114. * @param integer $duration the number of seconds in which the cached value will expire. 0 means never expire.
  115. * @return boolean true if the value is successfully stored into cache, false otherwise
  116. */
  117. protected function setValue($key, $value, $duration)
  118. {
  119. $cacheFile = $this->getCacheFile($key);
  120. if ($this->directoryLevel > 0) {
  121. @FileHelper::createDirectory(dirname($cacheFile), $this->dirMode, true);
  122. }
  123. if (@file_put_contents($cacheFile, $value, LOCK_EX) !== false) {
  124. if ($this->fileMode !== null) {
  125. @chmod($cacheFile, $this->fileMode);
  126. }
  127. if ($duration <= 0) {
  128. $duration = 31536000; // 1 year
  129. }
  130. return @touch($cacheFile, $duration + time());
  131. } else {
  132. return false;
  133. }
  134. }
  135. /**
  136. * Stores a value identified by a key into cache if the cache does not contain this key.
  137. * This is the implementation of the method declared in the parent class.
  138. *
  139. * @param string $key the key identifying the value to be cached
  140. * @param string $value the value to be cached
  141. * @param integer $duration the number of seconds in which the cached value will expire. 0 means never expire.
  142. * @return boolean true if the value is successfully stored into cache, false otherwise
  143. */
  144. protected function addValue($key, $value, $duration)
  145. {
  146. $cacheFile = $this->getCacheFile($key);
  147. if (@filemtime($cacheFile) > time()) {
  148. return false;
  149. }
  150. return $this->setValue($key, $value, $duration);
  151. }
  152. /**
  153. * Deletes a value with the specified key from cache
  154. * This is the implementation of the method declared in the parent class.
  155. * @param string $key the key of the value to be deleted
  156. * @return boolean if no error happens during deletion
  157. */
  158. protected function deleteValue($key)
  159. {
  160. $cacheFile = $this->getCacheFile($key);
  161. return @unlink($cacheFile);
  162. }
  163. /**
  164. * Returns the cache file path given the cache key.
  165. * @param string $key cache key
  166. * @return string the cache file path
  167. */
  168. protected function getCacheFile($key)
  169. {
  170. if ($this->directoryLevel > 0) {
  171. $base = $this->cachePath;
  172. for ($i = 0; $i < $this->directoryLevel; ++$i) {
  173. if (($prefix = substr($key, $i + $i, 2)) !== false) {
  174. $base .= DIRECTORY_SEPARATOR . $prefix;
  175. }
  176. }
  177. return $base . DIRECTORY_SEPARATOR . $key . $this->cacheFileSuffix;
  178. } else {
  179. return $this->cachePath . DIRECTORY_SEPARATOR . $key . $this->cacheFileSuffix;
  180. }
  181. }
  182. /**
  183. * Deletes all values from cache.
  184. * This is the implementation of the method declared in the parent class.
  185. * @return boolean whether the flush operation was successful.
  186. */
  187. protected function flushValues()
  188. {
  189. $this->gc(true, false);
  190. return true;
  191. }
  192. /**
  193. * Removes expired cache files.
  194. * @param boolean $force whether to enforce the garbage collection regardless of [[gcProbability]].
  195. * Defaults to false, meaning the actual deletion happens with the probability as specified by [[gcProbability]].
  196. * @param boolean $expiredOnly whether to removed expired cache files only.
  197. * If false, all cache files under [[cachePath]] will be removed.
  198. */
  199. public function gc($force = false, $expiredOnly = true)
  200. {
  201. if ($force || mt_rand(0, 1000000) < $this->gcProbability) {
  202. $this->gcRecursive($this->cachePath, $expiredOnly);
  203. }
  204. }
  205. /**
  206. * Recursively removing expired cache files under a directory.
  207. * This method is mainly used by [[gc()]].
  208. * @param string $path the directory under which expired cache files are removed.
  209. * @param boolean $expiredOnly whether to only remove expired cache files. If false, all files
  210. * under `$path` will be removed.
  211. */
  212. protected function gcRecursive($path, $expiredOnly)
  213. {
  214. if (($handle = opendir($path)) !== false) {
  215. while (($file = readdir($handle)) !== false) {
  216. if ($file[0] === '.') {
  217. continue;
  218. }
  219. $fullPath = $path . DIRECTORY_SEPARATOR . $file;
  220. if (is_dir($fullPath)) {
  221. $this->gcRecursive($fullPath, $expiredOnly);
  222. if (!$expiredOnly) {
  223. if (!@rmdir($fullPath)) {
  224. $error = error_get_last();
  225. Yii::warning("Unable to remove directory '{$fullPath}': {$error['message']}", __METHOD__);
  226. }
  227. }
  228. } elseif (!$expiredOnly || $expiredOnly && @filemtime($fullPath) < time()) {
  229. if (!@unlink($fullPath)) {
  230. $error = error_get_last();
  231. Yii::warning("Unable to remove file '{$fullPath}': {$error['message']}", __METHOD__);
  232. }
  233. }
  234. }
  235. closedir($handle);
  236. }
  237. }
  238. }