EMongoCache.php 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280
  1. <?php
  2. /**
  3. * Extends the Yii class 'CCache' to store cached data in mongoDB.
  4. *
  5. * PHP version 5.2+
  6. * MongoDB version >= 1.5.3
  7. * required extensions: MongoYii (for the configuration of the mongoDB connection)
  8. *
  9. * @author Zoltan Rajcsanyi <rajcsanyiz@gmail.com>
  10. * @copyright 2013 Zoltan Rajcsanyi
  11. * @license New BSD License
  12. * @category Database
  13. * @version 1.0
  14. */
  15. /**
  16. * EMongoCache implements a cache application component by storing cached data in a mongodb.
  17. *
  18. * EMongoDBCache stores cache data in a collection named {@link collectionName}.
  19. * If the collection does not exist, it will be automatically created.
  20. *
  21. * See {@link CCache} manual for common cache operations that are supported by EMongoCache.
  22. */
  23. class EMongoCache extends CCache
  24. {
  25. public $connectionID;
  26. /**
  27. * @var string name of the collection to store cache content. Defaults to 'YiiCache'.
  28. * The items are stored withe following structure:
  29. * <pre>
  30. * key: string,
  31. * value: string
  32. * expire: integer
  33. * </pre>
  34. */
  35. public $collectionName = 'YiiCache';
  36. public $ensureIndex = true; //set to false after first use of the cache
  37. /**
  38. * @var EMongoClient the DB connection instance
  39. */
  40. private $_db;
  41. private $_gcProbability = 100;
  42. private $_gced = false;
  43. /**
  44. * Initializes this application component.
  45. * ensureIndex 'key' if $ensureIndex = true
  46. * Set $ensureIndex to false after first use to increase performance
  47. *
  48. * This method is required by the {@link IApplicationComponent} interface.
  49. * It ensures the existence of the cache DB table.
  50. * It also removes expired data items from the cache.
  51. */
  52. public function init()
  53. {
  54. parent::init();
  55. if($this->ensureIndex){
  56. $this->getCollection()->ensureIndex( array('key' => 1)); // create index on "key"
  57. }
  58. }
  59. /**
  60. * @return EMongoClient the DB connection instance
  61. * @throws CException if {@link connectionID} does not point to a valid application component.
  62. */
  63. protected function getDbConnection()
  64. {
  65. if($this->_db !== null){
  66. return $this->_db;
  67. }elseif(($id = $this->connectionID) !== null){
  68. if(($this->_db = Yii::app()->getComponent($id)) instanceof EMongoClient){
  69. return $this->_db;
  70. }else{
  71. throw new CException(
  72. Yii::t(
  73. 'yii',
  74. 'EMongoCache.connectionID "{id}" is invalid. Please make sure it refers to the ID of a EMongoClient application component.',
  75. array('{id}'=>$id)
  76. )
  77. );
  78. }
  79. }else{
  80. return $this->_db = Yii::app()->getComponent('mongodb');
  81. }
  82. }
  83. /**
  84. * Returns current MongoCollection object
  85. *
  86. * @return MongoCollection
  87. */
  88. protected function getCollection()
  89. {
  90. return $this->getDbConnection()->{$this->collectionName};
  91. }
  92. /**
  93. * @return integer the probability (parts per million) that garbage collection (GC) should be performed
  94. * when storing a piece of data in the cache. Defaults to 100, meaning 0.01% chance.
  95. * @since 1.0.9
  96. */
  97. public function getGCProbability()
  98. {
  99. return $this->_gcProbability;
  100. }
  101. /**
  102. * @param integer $value the probability (parts per million) that garbage collection (GC) should be performed
  103. * when storing a piece of data in the cache. Defaults to 100, meaning 0.01% chance.
  104. * This number should be between 0 and 1000000. A value 0 meaning no GC will be performed at all.
  105. * @since 1.0.9
  106. */
  107. public function setGCProbability($value)
  108. {
  109. $value=(int)$value;
  110. if($value < 0){
  111. $value = 0;
  112. }elseif($value > 1000000){
  113. $value = 1000000;
  114. }
  115. $this->_gcProbability=$value;
  116. }
  117. /**
  118. * Retrieves a value from cache with a specified key.
  119. * This is the implementation of the method declared in the parent class.
  120. * @param string $key a unique key identifying the cached value
  121. * @return string the value stored in cache, false if the value is not in the cache or expired.
  122. */
  123. protected function getValue($key)
  124. {
  125. $time = time();
  126. $criteria = array(
  127. 'key' => (string)$key,
  128. '$or' => array(
  129. array('expire' => 0),
  130. array('expire' => array('$gt'=> $time)),
  131. ),
  132. );
  133. $data = $this->getCollection()->findOne($criteria);
  134. return $data === null ? '' : $data['value'];
  135. }
  136. /**
  137. * Retrieves multiple values from cache with the specified keys.
  138. * @param array $keys a list of keys identifying the cached values
  139. * @return array a list of cached values indexed by the keys
  140. */
  141. protected function getValues($keys)
  142. {
  143. if(empty($keys)){
  144. return array();
  145. }
  146. $results = array();
  147. $time = time();
  148. $criteria = array(
  149. 'key' => array('$in' => $keys),
  150. '$or' => array(
  151. array('expire' => 0),
  152. array('expire' => array('$gt'=> $time)),
  153. ),
  154. );
  155. $data = $this->getCollection()->find($criteria);
  156. if(!empty($data) && $data->count()){
  157. foreach($data as $id => $value){
  158. $results[$value['key']] = $value['value'];
  159. }
  160. }
  161. return $results;
  162. }
  163. /**
  164. * Stores a value identified by a key in cache.
  165. * This is the implementation of the method declared in the parent class.
  166. *
  167. * @param string $key the key identifying the value to be cached
  168. * @param string $value the value to be cached
  169. * @param integer $expire the number of seconds in which the cached value will expire. 0 means never expire.
  170. * @return boolean true if the value is successfully stored into cache, false otherwise
  171. */
  172. protected function setValue($key, $value, $expire)
  173. {
  174. return $this->addValue($key, $value, $expire);
  175. }
  176. /**
  177. * Stores a value identified by a key into cache if the cache does not contain this key.
  178. * This is the implementation of the method declared in the parent class.
  179. *
  180. * If the key exists the value will be updated, otherwise inserted
  181. *
  182. * @param string $key the key identifying the value to be cached
  183. * @param string $value the value to be cached
  184. * @param integer $expire the number of seconds in which the cached value will expire. 0 means never expire.
  185. * @return boolean true if the value is successfully stored into cache, false otherwise
  186. */
  187. protected function addValue($key, $value, $expire)
  188. {
  189. if(!$this->_gced && mt_rand(0,1000000) < $this->_gcProbability){
  190. $this->gc();
  191. $this->_gced = true;
  192. }
  193. if($expire > 0){
  194. $expire += time();
  195. }else{
  196. $expire = 0;
  197. }
  198. $criteria = array('key' => (string)$key);
  199. $data = array(
  200. 'key' => (string)$key,
  201. 'value' => (string)$value,
  202. 'expire' => (int)$expire,
  203. );
  204. $options = array('upsert' => true);
  205. try{
  206. return $this->getCollection()->update($criteria, $data, $options);
  207. }catch(Exception $e){
  208. return false;
  209. }
  210. }
  211. /**
  212. * Deletes a value with the specified key from cache
  213. * This is the implementation of the method declared in the parent class.
  214. * @param string $key the key of the value to be deleted
  215. * @return boolean if no error happens during deletion
  216. */
  217. protected function deleteValue($key)
  218. {
  219. $criteria = array('key' => (string)$key);
  220. $data = $this->getCollection()->remove($criteria);
  221. return true;
  222. }
  223. /**
  224. * Removes the expired data values.
  225. */
  226. protected function gc()
  227. {
  228. //delete expired entries
  229. $criteria = array(
  230. 'expired' => array('$gt' => 0),
  231. 'expired' => array('$lt' => time()),
  232. );
  233. $this->getCollection()->remove($criteria);
  234. }
  235. /**
  236. * Deletes all values from cache.
  237. * This is the implementation of the method declared in the parent class.
  238. * @return boolean whether the flush operation was successful.
  239. */
  240. protected function flushValues()
  241. {
  242. $this->getCollection()->remove();
  243. return true;
  244. }
  245. }