PageRenderTime 40ms CodeModel.GetById 12ms RepoModel.GetById 0ms app.codeStats 0ms

/yii/framework/caching/CCache.php

https://github.com/joshuaswarren/weatherhub
PHP | 334 lines | 127 code | 19 blank | 188 comment | 11 complexity | f1fec9ed4106f82af3189693fde0539e MD5 | raw file
  1. <?php
  2. /**
  3. * CCache class file.
  4. *
  5. * @author Qiang Xue <qiang.xue@gmail.com>
  6. * @link http://www.yiiframework.com/
  7. * @copyright Copyright &copy; 2008-2011 Yii Software LLC
  8. * @license http://www.yiiframework.com/license/
  9. */
  10. /**
  11. * CCache is the base class for cache classes with different cache storage implementation.
  12. *
  13. * A data item can be stored in cache by calling {@link set} and be retrieved back
  14. * later by {@link get}. In both operations, a key identifying the data item is required.
  15. * An expiration time and/or a dependency can also be specified when calling {@link set}.
  16. * If the data item expires or the dependency changes, calling {@link get} will not
  17. * return back the data item.
  18. *
  19. * Note, by definition, cache does not ensure the existence of a value
  20. * even if it does not expire. Cache is not meant to be a persistent storage.
  21. *
  22. * CCache implements the interface {@link ICache} with the following methods:
  23. * <ul>
  24. * <li>{@link get} : retrieve the value with a key (if any) from cache</li>
  25. * <li>{@link set} : store the value with a key into cache</li>
  26. * <li>{@link add} : store the value only if cache does not have this key</li>
  27. * <li>{@link delete} : delete the value with the specified key from cache</li>
  28. * <li>{@link flush} : delete all values from cache</li>
  29. * </ul>
  30. *
  31. * Child classes must implement the following methods:
  32. * <ul>
  33. * <li>{@link getValue}</li>
  34. * <li>{@link setValue}</li>
  35. * <li>{@link addValue}</li>
  36. * <li>{@link deleteValue}</li>
  37. * <li>{@link flush} (optional)</li>
  38. * </ul>
  39. *
  40. * CCache also implements ArrayAccess so that it can be used like an array.
  41. *
  42. * @author Qiang Xue <qiang.xue@gmail.com>
  43. * @version $Id: CCache.php 3001 2011-02-24 16:42:44Z alexander.makarow $
  44. * @package system.caching
  45. * @since 1.0
  46. */
  47. abstract class CCache extends CApplicationComponent implements ICache, ArrayAccess
  48. {
  49. /**
  50. * @var string a string prefixed to every cache key so that it is unique. Defaults to {@link CApplication::getId() application ID}.
  51. */
  52. public $keyPrefix;
  53. /**
  54. * Initializes the application component.
  55. * This method overrides the parent implementation by setting default cache key prefix.
  56. */
  57. public function init()
  58. {
  59. parent::init();
  60. if($this->keyPrefix===null)
  61. $this->keyPrefix=Yii::app()->getId();
  62. }
  63. /**
  64. * @param string $key a key identifying a value to be cached
  65. * @return sring a key generated from the provided key which ensures the uniqueness across applications
  66. */
  67. protected function generateUniqueKey($key)
  68. {
  69. return md5($this->keyPrefix.$key);
  70. }
  71. /**
  72. * Retrieves a value from cache with a specified key.
  73. * @param string $id a key identifying the cached value
  74. * @return mixed the value stored in cache, false if the value is not in the cache, expired or the dependency has changed.
  75. */
  76. public function get($id)
  77. {
  78. if(($value=$this->getValue($this->generateUniqueKey($id)))!==false)
  79. {
  80. $data=unserialize($value);
  81. if(!is_array($data))
  82. return false;
  83. if(!($data[1] instanceof ICacheDependency) || !$data[1]->getHasChanged())
  84. {
  85. Yii::trace('Serving "'.$id.'" from cache','system.caching.'.get_class($this));
  86. return $data[0];
  87. }
  88. }
  89. return false;
  90. }
  91. /**
  92. * Retrieves multiple values from cache with the specified keys.
  93. * Some caches (such as memcache, apc) allow retrieving multiple cached values at one time,
  94. * which may improve the performance since it reduces the communication cost.
  95. * In case a cache doesn't support this feature natively, it will be simulated by this method.
  96. * @param array $ids list of keys identifying the cached values
  97. * @return array list of cached values corresponding to the specified keys. The array
  98. * is returned in terms of (key,value) pairs.
  99. * If a value is not cached or expired, the corresponding array value will be false.
  100. * @since 1.0.8
  101. */
  102. public function mget($ids)
  103. {
  104. $uniqueIDs=array();
  105. $results=array();
  106. foreach($ids as $id)
  107. {
  108. $uniqueIDs[$id]=$this->generateUniqueKey($id);
  109. $results[$id]=false;
  110. }
  111. $values=$this->getValues($uniqueIDs);
  112. foreach($uniqueIDs as $id=>$uniqueID)
  113. {
  114. if(!isset($values[$uniqueID]))
  115. continue;
  116. $data=unserialize($values[$uniqueID]);
  117. if(is_array($data) && (!($data[1] instanceof ICacheDependency) || !$data[1]->getHasChanged()))
  118. {
  119. Yii::trace('Serving "'.$id.'" from cache','system.caching.'.get_class($this));
  120. $results[$id]=$data[0];
  121. }
  122. }
  123. return $results;
  124. }
  125. /**
  126. * Stores a value identified by a key into cache.
  127. * If the cache already contains such a key, the existing value and
  128. * expiration time will be replaced with the new ones.
  129. *
  130. * @param string $id the key identifying the value to be cached
  131. * @param mixed $value the value to be cached
  132. * @param integer $expire the number of seconds in which the cached value will expire. 0 means never expire.
  133. * @param ICacheDependency $dependency dependency of the cached item. If the dependency changes, the item is labeled invalid.
  134. * @return boolean true if the value is successfully stored into cache, false otherwise
  135. */
  136. public function set($id,$value,$expire=0,$dependency=null)
  137. {
  138. Yii::trace('Saving "'.$id.'" to cache','system.caching.'.get_class($this));
  139. if($dependency!==null)
  140. $dependency->evaluateDependency();
  141. $data=array($value,$dependency);
  142. return $this->setValue($this->generateUniqueKey($id),serialize($data),$expire);
  143. }
  144. /**
  145. * Stores a value identified by a key into cache if the cache does not contain this key.
  146. * Nothing will be done if the cache already contains the key.
  147. * @param string $id the key identifying the value to be cached
  148. * @param mixed $value the value to be cached
  149. * @param integer $expire the number of seconds in which the cached value will expire. 0 means never expire.
  150. * @param ICacheDependency $dependency dependency of the cached item. If the dependency changes, the item is labeled invalid.
  151. * @return boolean true if the value is successfully stored into cache, false otherwise
  152. */
  153. public function add($id,$value,$expire=0,$dependency=null)
  154. {
  155. Yii::trace('Adding "'.$id.'" to cache','system.caching.'.get_class($this));
  156. if($dependency!==null)
  157. $dependency->evaluateDependency();
  158. $data=array($value,$dependency);
  159. return $this->addValue($this->generateUniqueKey($id),serialize($data),$expire);
  160. }
  161. /**
  162. * Deletes a value with the specified key from cache
  163. * @param string $id the key of the value to be deleted
  164. * @return boolean if no error happens during deletion
  165. */
  166. public function delete($id)
  167. {
  168. Yii::trace('Deleting "'.$id.'" from cache','system.caching.'.get_class($this));
  169. return $this->deleteValue($this->generateUniqueKey($id));
  170. }
  171. /**
  172. * Deletes all values from cache.
  173. * Be careful of performing this operation if the cache is shared by multiple applications.
  174. * @return boolean whether the flush operation was successful.
  175. */
  176. public function flush()
  177. {
  178. Yii::trace('Flushing cache','system.caching.'.get_class($this));
  179. return $this->flushValues();
  180. }
  181. /**
  182. * Retrieves a value from cache with a specified key.
  183. * This method should be implemented by child classes to retrieve the data
  184. * from specific cache storage. The uniqueness and dependency are handled
  185. * in {@link get()} already. So only the implementation of data retrieval
  186. * is needed.
  187. * @param string $key a unique key identifying the cached value
  188. * @return string the value stored in cache, false if the value is not in the cache or expired.
  189. * @throws CException if this method is not overridden by child classes
  190. */
  191. protected function getValue($key)
  192. {
  193. throw new CException(Yii::t('yii','{className} does not support get() functionality.',
  194. array('{className}'=>get_class($this))));
  195. }
  196. /**
  197. * Retrieves multiple values from cache with the specified keys.
  198. * The default implementation simply calls {@link getValue} multiple
  199. * times to retrieve the cached values one by one.
  200. * If the underlying cache storage supports multiget, this method should
  201. * be overridden to exploit that feature.
  202. * @param array $keys a list of keys identifying the cached values
  203. * @return array a list of cached values indexed by the keys
  204. * @since 1.0.8
  205. */
  206. protected function getValues($keys)
  207. {
  208. $results=array();
  209. foreach($keys as $key)
  210. $results[$key]=$this->getValue($key);
  211. return $results;
  212. }
  213. /**
  214. * Stores a value identified by a key in cache.
  215. * This method should be implemented by child classes to store the data
  216. * in specific cache storage. The uniqueness and dependency are handled
  217. * in {@link set()} already. So only the implementation of data storage
  218. * is needed.
  219. *
  220. * @param string $key the key identifying the value to be cached
  221. * @param string $value the value to be cached
  222. * @param integer $expire the number of seconds in which the cached value will expire. 0 means never expire.
  223. * @return boolean true if the value is successfully stored into cache, false otherwise
  224. * @throws CException if this method is not overridden by child classes
  225. */
  226. protected function setValue($key,$value,$expire)
  227. {
  228. throw new CException(Yii::t('yii','{className} does not support set() functionality.',
  229. array('{className}'=>get_class($this))));
  230. }
  231. /**
  232. * Stores a value identified by a key into cache if the cache does not contain this key.
  233. * This method should be implemented by child classes to store the data
  234. * in specific cache storage. The uniqueness and dependency are handled
  235. * in {@link add()} already. So only the implementation of data storage
  236. * is needed.
  237. *
  238. * @param string $key the key identifying the value to be cached
  239. * @param string $value the value to be cached
  240. * @param integer $expire the number of seconds in which the cached value will expire. 0 means never expire.
  241. * @return boolean true if the value is successfully stored into cache, false otherwise
  242. * @throws CException if this method is not overridden by child classes
  243. */
  244. protected function addValue($key,$value,$expire)
  245. {
  246. throw new CException(Yii::t('yii','{className} does not support add() functionality.',
  247. array('{className}'=>get_class($this))));
  248. }
  249. /**
  250. * Deletes a value with the specified key from cache
  251. * This method should be implemented by child classes to delete the data from actual cache storage.
  252. * @param string $key the key of the value to be deleted
  253. * @return boolean if no error happens during deletion
  254. * @throws CException if this method is not overridden by child classes
  255. */
  256. protected function deleteValue($key)
  257. {
  258. throw new CException(Yii::t('yii','{className} does not support delete() functionality.',
  259. array('{className}'=>get_class($this))));
  260. }
  261. /**
  262. * Deletes all values from cache.
  263. * Child classes may implement this method to realize the flush operation.
  264. * @return boolean whether the flush operation was successful.
  265. * @throws CException if this method is not overridden by child classes
  266. * @since 1.1.5
  267. */
  268. protected function flushValues()
  269. {
  270. throw new CException(Yii::t('yii','{className} does not support flushValues() functionality.',
  271. array('{className}'=>get_class($this))));
  272. }
  273. /**
  274. * Returns whether there is a cache entry with a specified key.
  275. * This method is required by the interface ArrayAccess.
  276. * @param string $id a key identifying the cached value
  277. * @return boolean
  278. */
  279. public function offsetExists($id)
  280. {
  281. return $this->get($id)!==false;
  282. }
  283. /**
  284. * Retrieves the value from cache with a specified key.
  285. * This method is required by the interface ArrayAccess.
  286. * @param string $id a key identifying the cached value
  287. * @return mixed the value stored in cache, false if the value is not in the cache or expired.
  288. */
  289. public function offsetGet($id)
  290. {
  291. return $this->get($id);
  292. }
  293. /**
  294. * Stores the value identified by a key into cache.
  295. * If the cache already contains such a key, the existing value will be
  296. * replaced with the new ones. To add expiration and dependencies, use the set() method.
  297. * This method is required by the interface ArrayAccess.
  298. * @param string $id the key identifying the value to be cached
  299. * @param mixed $value the value to be cached
  300. */
  301. public function offsetSet($id, $value)
  302. {
  303. $this->set($id, $value);
  304. }
  305. /**
  306. * Deletes the value with the specified key from cache
  307. * This method is required by the interface ArrayAccess.
  308. * @param string $id the key of the value to be deleted
  309. * @return boolean if no error happens during deletion
  310. */
  311. public function offsetUnset($id)
  312. {
  313. $this->delete($id);
  314. }
  315. }