CCache.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376
  1. <?php
  2. /**
  3. * CCache 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. * 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 getValues} (optional)</li>
  38. * <li>{@link flushValues} (optional)</li>
  39. * <li>{@link serializer} (optional)</li>
  40. * </ul>
  41. *
  42. * CCache also implements ArrayAccess so that it can be used like an array.
  43. *
  44. * @author Qiang Xue <qiang.xue@gmail.com>
  45. * @package system.caching
  46. * @since 1.0
  47. */
  48. abstract class CCache extends CApplicationComponent implements ICache, ArrayAccess
  49. {
  50. /**
  51. * @var string a string prefixed to every cache key so that it is unique. Defaults to null which means
  52. * to use the {@link CApplication::getId() application ID}. If different applications need to access the same
  53. * pool of cached data, the same prefix should be set for each of the applications explicitly.
  54. */
  55. public $keyPrefix;
  56. /**
  57. * @var boolean whether to md5-hash the cache key for normalization purposes. Defaults to true. Setting this property to false makes sure the cache
  58. * key will not be tampered when calling the relevant methods {@link get()}, {@link set()}, {@link add()} and {@link delete()}. This is useful if a Yii
  59. * application as well as an external application need to access the same cache pool (also see description of {@link keyPrefix} regarding this use case).
  60. * However, without normalization you should make sure the affected cache backend does support the structure (charset, length, etc.) of all the provided
  61. * cache keys, otherwise there might be unexpected behavior.
  62. * @since 1.1.11
  63. **/
  64. public $hashKey=true;
  65. /**
  66. * @var array|boolean the functions used to serialize and unserialize cached data. Defaults to null, meaning
  67. * using the default PHP `serialize()` and `unserialize()` functions. If you want to use some more efficient
  68. * serializer (e.g. {@link http://pecl.php.net/package/igbinary igbinary}), you may configure this property with
  69. * a two-element array. The first element specifies the serialization function, and the second the deserialization
  70. * function. If this property is set false, data will be directly sent to and retrieved from the underlying
  71. * cache component without any serialization or deserialization. You should not turn off serialization if
  72. * you are using {@link CCacheDependency cache dependency}, because it relies on data serialization.
  73. */
  74. public $serializer;
  75. /**
  76. * Initializes the application component.
  77. * This method overrides the parent implementation by setting default cache key prefix.
  78. */
  79. public function init()
  80. {
  81. parent::init();
  82. if($this->keyPrefix===null)
  83. $this->keyPrefix=Yii::app()->getId();
  84. }
  85. /**
  86. * @param string $key a key identifying a value to be cached
  87. * @return string a key generated from the provided key which ensures the uniqueness across applications
  88. */
  89. protected function generateUniqueKey($key)
  90. {
  91. return $this->hashKey ? md5($this->keyPrefix.$key) : $this->keyPrefix.$key;
  92. }
  93. /**
  94. * Retrieves a value from cache with a specified key.
  95. * @param string $id a key identifying the cached value
  96. * @return mixed the value stored in cache, false if the value is not in the cache, expired or the dependency has changed.
  97. */
  98. public function get($id)
  99. {
  100. $value = $this->getValue($this->generateUniqueKey($id));
  101. if($value===false || $this->serializer===false)
  102. return $value;
  103. if($this->serializer===null)
  104. $value=unserialize($value);
  105. else
  106. $value=call_user_func($this->serializer[1], $value);
  107. if(is_array($value) && (!$value[1] instanceof ICacheDependency || !$value[1]->getHasChanged()))
  108. {
  109. Yii::trace('Serving "'.$id.'" from cache','system.caching.'.get_class($this));
  110. return $value[0];
  111. }
  112. else
  113. return false;
  114. }
  115. /**
  116. * Retrieves multiple values from cache with the specified keys.
  117. * Some caches (such as memcache, apc) allow retrieving multiple cached values at one time,
  118. * which may improve the performance since it reduces the communication cost.
  119. * In case a cache does not support this feature natively, it will be simulated by this method.
  120. * @param array $ids list of keys identifying the cached values
  121. * @return array list of cached values corresponding to the specified keys. The array
  122. * is returned in terms of (key,value) pairs.
  123. * If a value is not cached or expired, the corresponding array value will be false.
  124. */
  125. public function mget($ids)
  126. {
  127. $uids = array();
  128. foreach ($ids as $id)
  129. $uids[$id] = $this->generateUniqueKey($id);
  130. $values = $this->getValues($uids);
  131. $results = array();
  132. if($this->serializer === false)
  133. {
  134. foreach ($uids as $id => $uid)
  135. $results[$id] = isset($values[$uid]) ? $values[$uid] : false;
  136. }
  137. else
  138. {
  139. foreach($uids as $id => $uid)
  140. {
  141. $results[$id] = false;
  142. if(isset($values[$uid]))
  143. {
  144. $value = $this->serializer === null ? unserialize($values[$uid]) : call_user_func($this->serializer[1], $values[$uid]);
  145. if(is_array($value) && (!$value[1] instanceof ICacheDependency || !$value[1]->getHasChanged()))
  146. {
  147. Yii::trace('Serving "'.$id.'" from cache','system.caching.'.get_class($this));
  148. $results[$id] = $value[0];
  149. }
  150. }
  151. }
  152. }
  153. return $results;
  154. }
  155. /**
  156. * Stores a value identified by a key into cache.
  157. * If the cache already contains such a key, the existing value and
  158. * expiration time will be replaced with the new ones.
  159. *
  160. * @param string $id the key identifying the value to be cached
  161. * @param mixed $value the value to be cached
  162. * @param integer $expire the number of seconds in which the cached value will expire. 0 means never expire.
  163. * @param ICacheDependency $dependency dependency of the cached item. If the dependency changes, the item is labeled invalid.
  164. * @return boolean true if the value is successfully stored into cache, false otherwise
  165. */
  166. public function set($id,$value,$expire=0,$dependency=null)
  167. {
  168. Yii::trace('Saving "'.$id.'" to cache','system.caching.'.get_class($this));
  169. if ($dependency !== null && $this->serializer !== false)
  170. $dependency->evaluateDependency();
  171. if ($this->serializer === null)
  172. $value = serialize(array($value,$dependency));
  173. elseif ($this->serializer !== false)
  174. $value = call_user_func($this->serializer[0], array($value,$dependency));
  175. return $this->setValue($this->generateUniqueKey($id), $value, $expire);
  176. }
  177. /**
  178. * Stores a value identified by a key into cache if the cache does not contain this key.
  179. * Nothing will be done if the cache already contains the key.
  180. * @param string $id the key identifying the value to be cached
  181. * @param mixed $value the value to be cached
  182. * @param integer $expire the number of seconds in which the cached value will expire. 0 means never expire.
  183. * @param ICacheDependency $dependency dependency of the cached item. If the dependency changes, the item is labeled invalid.
  184. * @return boolean true if the value is successfully stored into cache, false otherwise
  185. */
  186. public function add($id,$value,$expire=0,$dependency=null)
  187. {
  188. Yii::trace('Adding "'.$id.'" to cache','system.caching.'.get_class($this));
  189. if ($dependency !== null && $this->serializer !== false)
  190. $dependency->evaluateDependency();
  191. if ($this->serializer === null)
  192. $value = serialize(array($value,$dependency));
  193. elseif ($this->serializer !== false)
  194. $value = call_user_func($this->serializer[0], array($value,$dependency));
  195. return $this->addValue($this->generateUniqueKey($id), $value, $expire);
  196. }
  197. /**
  198. * Deletes a value with the specified key from cache
  199. * @param string $id the key of the value to be deleted
  200. * @return boolean if no error happens during deletion
  201. */
  202. public function delete($id)
  203. {
  204. Yii::trace('Deleting "'.$id.'" from cache','system.caching.'.get_class($this));
  205. return $this->deleteValue($this->generateUniqueKey($id));
  206. }
  207. /**
  208. * Deletes all values from cache.
  209. * Be careful of performing this operation if the cache is shared by multiple applications.
  210. * @return boolean whether the flush operation was successful.
  211. */
  212. public function flush()
  213. {
  214. Yii::trace('Flushing cache','system.caching.'.get_class($this));
  215. return $this->flushValues();
  216. }
  217. /**
  218. * Retrieves a value from cache with a specified key.
  219. * This method should be implemented by child classes to retrieve the data
  220. * from specific cache storage. The uniqueness and dependency are handled
  221. * in {@link get()} already. So only the implementation of data retrieval
  222. * is needed.
  223. * @param string $key a unique key identifying the cached value
  224. * @return string|boolean the value stored in cache, false if the value is not in the cache or expired.
  225. * @throws CException if this method is not overridden by child classes
  226. */
  227. protected function getValue($key)
  228. {
  229. throw new CException(Yii::t('yii','{className} does not support get() functionality.',
  230. array('{className}'=>get_class($this))));
  231. }
  232. /**
  233. * Retrieves multiple values from cache with the specified keys.
  234. * The default implementation simply calls {@link getValue} multiple
  235. * times to retrieve the cached values one by one.
  236. * If the underlying cache storage supports multiget, this method should
  237. * be overridden to exploit that feature.
  238. * @param array $keys a list of keys identifying the cached values
  239. * @return array a list of cached values indexed by the keys
  240. */
  241. protected function getValues($keys)
  242. {
  243. $results=array();
  244. foreach($keys as $key)
  245. $results[$key]=$this->getValue($key);
  246. return $results;
  247. }
  248. /**
  249. * Stores a value identified by a key in cache.
  250. * This method should be implemented by child classes to store the data
  251. * in specific cache storage. The uniqueness and dependency are handled
  252. * in {@link set()} already. So only the implementation of data storage
  253. * is needed.
  254. *
  255. * @param string $key the key identifying the value to be cached
  256. * @param string $value the value to be cached
  257. * @param integer $expire the number of seconds in which the cached value will expire. 0 means never expire.
  258. * @return boolean true if the value is successfully stored into cache, false otherwise
  259. * @throws CException if this method is not overridden by child classes
  260. */
  261. protected function setValue($key,$value,$expire)
  262. {
  263. throw new CException(Yii::t('yii','{className} does not support set() functionality.',
  264. array('{className}'=>get_class($this))));
  265. }
  266. /**
  267. * Stores a value identified by a key into cache if the cache does not contain this key.
  268. * This method should be implemented by child classes to store the data
  269. * in specific cache storage. The uniqueness and dependency are handled
  270. * in {@link add()} already. So only the implementation of data storage
  271. * is needed.
  272. *
  273. * @param string $key the key identifying the value to be cached
  274. * @param string $value the value to be cached
  275. * @param integer $expire the number of seconds in which the cached value will expire. 0 means never expire.
  276. * @return boolean true if the value is successfully stored into cache, false otherwise
  277. * @throws CException if this method is not overridden by child classes
  278. */
  279. protected function addValue($key,$value,$expire)
  280. {
  281. throw new CException(Yii::t('yii','{className} does not support add() functionality.',
  282. array('{className}'=>get_class($this))));
  283. }
  284. /**
  285. * Deletes a value with the specified key from cache
  286. * This method should be implemented by child classes to delete the data from actual cache storage.
  287. * @param string $key the key of the value to be deleted
  288. * @return boolean if no error happens during deletion
  289. * @throws CException if this method is not overridden by child classes
  290. */
  291. protected function deleteValue($key)
  292. {
  293. throw new CException(Yii::t('yii','{className} does not support delete() functionality.',
  294. array('{className}'=>get_class($this))));
  295. }
  296. /**
  297. * Deletes all values from cache.
  298. * Child classes may implement this method to realize the flush operation.
  299. * @return boolean whether the flush operation was successful.
  300. * @throws CException if this method is not overridden by child classes
  301. * @since 1.1.5
  302. */
  303. protected function flushValues()
  304. {
  305. throw new CException(Yii::t('yii','{className} does not support flushValues() functionality.',
  306. array('{className}'=>get_class($this))));
  307. }
  308. /**
  309. * Returns whether there is a cache entry with a specified key.
  310. * This method is required by the interface ArrayAccess.
  311. * @param string $id a key identifying the cached value
  312. * @return boolean
  313. */
  314. public function offsetExists($id)
  315. {
  316. return $this->get($id)!==false;
  317. }
  318. /**
  319. * Retrieves the value from cache with a specified key.
  320. * This method is required by the interface ArrayAccess.
  321. * @param string $id a key identifying the cached value
  322. * @return mixed the value stored in cache, false if the value is not in the cache or expired.
  323. */
  324. public function offsetGet($id)
  325. {
  326. return $this->get($id);
  327. }
  328. /**
  329. * Stores the value identified by a key into cache.
  330. * If the cache already contains such a key, the existing value will be
  331. * replaced with the new ones. To add expiration and dependencies, use the set() method.
  332. * This method is required by the interface ArrayAccess.
  333. * @param string $id the key identifying the value to be cached
  334. * @param mixed $value the value to be cached
  335. */
  336. public function offsetSet($id, $value)
  337. {
  338. $this->set($id, $value);
  339. }
  340. /**
  341. * Deletes the value with the specified key from cache
  342. * This method is required by the interface ArrayAccess.
  343. * @param string $id the key of the value to be deleted
  344. * @return boolean if no error happens during deletion
  345. */
  346. public function offsetUnset($id)
  347. {
  348. $this->delete($id);
  349. }
  350. }