CFileCache.php 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242
  1. <?php
  2. /**
  3. * CFileCache class file
  4. *
  5. * @author Qiang Xue <qiang.xue@gmail.com>
  6. * @link http://www.yiiframework.com/
  7. * @copyright 2008-2013 Yii Software LLC
  8. * @license http://www.yiiframework.com/license/
  9. */
  10. /**
  11. * CFileCache provides a file-based caching mechanism.
  12. *
  13. * For each data value being cached, CFileCache will use store it in a separate file
  14. * under {@link cachePath} which defaults to 'protected/runtime/cache'.
  15. * CFileCache will perform garbage collection automatically to remove expired cache files.
  16. *
  17. * See {@link CCache} manual for common cache operations that are supported by CFileCache.
  18. *
  19. * @property integer $gCProbability The probability (parts per million) that garbage collection (GC) should be performed
  20. * when storing a piece of data in the cache. Defaults to 100, meaning 0.01% chance.
  21. *
  22. * @author Qiang Xue <qiang.xue@gmail.com>
  23. * @package system.caching
  24. */
  25. class CFileCache extends CCache
  26. {
  27. /**
  28. * @var string the directory to store cache files. Defaults to null, meaning
  29. * using 'protected/runtime/cache' as the directory.
  30. */
  31. public $cachePath;
  32. /**
  33. * @var string cache file suffix. Defaults to '.bin'.
  34. */
  35. public $cacheFileSuffix='.bin';
  36. /**
  37. * @var integer the level of sub-directories to store cache files. Defaults to 0,
  38. * meaning no sub-directories. If the system has huge number of cache files (e.g. 10K+),
  39. * you may want to set this value to be 1 or 2 so that the file system is not over burdened.
  40. * The value of this property should not exceed 16 (less than 3 is recommended).
  41. */
  42. public $directoryLevel=0;
  43. /**
  44. * @var boolean whether cache entry expiration time should be embedded into a physical file.
  45. * Defaults to false meaning that the file modification time will be used to store expire value.
  46. * True value means that first ten bytes of the file would be reserved and used to store expiration time.
  47. * On some systems PHP is not allowed to change file modification time to be in future even with 777
  48. * permissions, so this property could be useful in this case.
  49. * @since 1.1.14
  50. */
  51. public $embedExpiry=false;
  52. private $_gcProbability=100;
  53. private $_gced=false;
  54. /**
  55. * Initializes this application component.
  56. * This method is required by the {@link IApplicationComponent} interface.
  57. */
  58. public function init()
  59. {
  60. parent::init();
  61. if($this->cachePath===null)
  62. $this->cachePath=Yii::app()->getRuntimePath().DIRECTORY_SEPARATOR.'cache';
  63. if(!is_dir($this->cachePath))
  64. mkdir($this->cachePath,0777,true);
  65. }
  66. /**
  67. * @return integer the probability (parts per million) that garbage collection (GC) should be performed
  68. * when storing a piece of data in the cache. Defaults to 100, meaning 0.01% chance.
  69. */
  70. public function getGCProbability()
  71. {
  72. return $this->_gcProbability;
  73. }
  74. /**
  75. * @param integer $value the probability (parts per million) that garbage collection (GC) should be performed
  76. * when storing a piece of data in the cache. Defaults to 100, meaning 0.01% chance.
  77. * This number should be between 0 and 1000000. A value 0 meaning no GC will be performed at all.
  78. */
  79. public function setGCProbability($value)
  80. {
  81. $value=(int)$value;
  82. if($value<0)
  83. $value=0;
  84. if($value>1000000)
  85. $value=1000000;
  86. $this->_gcProbability=$value;
  87. }
  88. /**
  89. * Deletes all values from cache.
  90. * This is the implementation of the method declared in the parent class.
  91. * @return boolean whether the flush operation was successful.
  92. * @since 1.1.5
  93. */
  94. protected function flushValues()
  95. {
  96. $this->gc(false);
  97. return true;
  98. }
  99. /**
  100. * Retrieves a value from cache with a specified key.
  101. * This is the implementation of the method declared in the parent class.
  102. * @param string $key a unique key identifying the cached value
  103. * @return string|boolean the value stored in cache, false if the value is not in the cache or expired.
  104. */
  105. protected function getValue($key)
  106. {
  107. $cacheFile=$this->getCacheFile($key);
  108. if(($time=$this->filemtime($cacheFile))>time())
  109. return @file_get_contents($cacheFile,false,null,$this->embedExpiry ? 10 : -1);
  110. elseif($time>0)
  111. @unlink($cacheFile);
  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 $expire 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,$expire)
  124. {
  125. if(!$this->_gced && mt_rand(0,1000000)<$this->_gcProbability)
  126. {
  127. $this->gc();
  128. $this->_gced=true;
  129. }
  130. if($expire<=0)
  131. $expire=31536000; // 1 year
  132. $expire+=time();
  133. $cacheFile=$this->getCacheFile($key);
  134. if($this->directoryLevel>0)
  135. @mkdir(dirname($cacheFile),0777,true);
  136. if(@file_put_contents($cacheFile,$this->embedExpiry ? $expire.$value : $value,LOCK_EX)!==false)
  137. {
  138. @chmod($cacheFile,0777);
  139. return $this->embedExpiry ? true : @touch($cacheFile,$expire);
  140. }
  141. else
  142. return false;
  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 $expire 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,$expire)
  154. {
  155. $cacheFile=$this->getCacheFile($key);
  156. if($this->filemtime($cacheFile)>time())
  157. return false;
  158. return $this->setValue($key,$value,$expire);
  159. }
  160. /**
  161. * Deletes a value with the specified key from cache
  162. * This is the implementation of the method declared in the parent class.
  163. * @param string $key the key of the value to be deleted
  164. * @return boolean if no error happens during deletion
  165. */
  166. protected function deleteValue($key)
  167. {
  168. $cacheFile=$this->getCacheFile($key);
  169. return @unlink($cacheFile);
  170. }
  171. /**
  172. * Returns the cache file path given the cache key.
  173. * @param string $key cache key
  174. * @return string the cache file path
  175. */
  176. protected function getCacheFile($key)
  177. {
  178. if($this->directoryLevel>0)
  179. {
  180. $base=$this->cachePath;
  181. for($i=0;$i<$this->directoryLevel;++$i)
  182. {
  183. if(($prefix=substr($key,$i+$i,2))!==false)
  184. $base.=DIRECTORY_SEPARATOR.$prefix;
  185. }
  186. return $base.DIRECTORY_SEPARATOR.$key.$this->cacheFileSuffix;
  187. }
  188. else
  189. return $this->cachePath.DIRECTORY_SEPARATOR.$key.$this->cacheFileSuffix;
  190. }
  191. /**
  192. * Removes expired cache files.
  193. * @param boolean $expiredOnly whether only expired cache files should be removed.
  194. * If false, all cache files under {@link cachePath} will be removed.
  195. * @param string $path the path to clean with. If null, it will be {@link cachePath}.
  196. */
  197. public function gc($expiredOnly=true,$path=null)
  198. {
  199. if($path===null)
  200. $path=$this->cachePath;
  201. if(($handle=opendir($path))===false)
  202. return;
  203. while(($file=readdir($handle))!==false)
  204. {
  205. if($file[0]==='.')
  206. continue;
  207. $fullPath=$path.DIRECTORY_SEPARATOR.$file;
  208. if(is_dir($fullPath))
  209. $this->gc($expiredOnly,$fullPath);
  210. elseif($expiredOnly && $this->filemtime($fullPath)<time() || !$expiredOnly)
  211. @unlink($fullPath);
  212. }
  213. closedir($handle);
  214. }
  215. /**
  216. * Returns cache file modification time. {@link $embedExpiry} aware.
  217. * @param string $path to the file, modification time to be retrieved from.
  218. * @return integer file modification time.
  219. */
  220. private function filemtime($path)
  221. {
  222. if($this->embedExpiry)
  223. return (int)@file_get_contents($path,false,null,0,10);
  224. else
  225. return @filemtime($path);
  226. }
  227. }