FileCache.php 8.0 KB

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