Cache.php 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198
  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\mongodb;
  8. use Yii;
  9. use yii\base\InvalidConfigException;
  10. use yii\di\Instance;
  11. /**
  12. * Cache implements a cache application component by storing cached data in a MongoDB.
  13. *
  14. * By default, Cache stores session data in a MongoDB collection named 'cache' inside the default database.
  15. * This collection is better to be pre-created with fields 'id' and 'expire' indexed.
  16. * The collection name can be changed by setting [[cacheCollection]].
  17. *
  18. * Please refer to [[\yii\caching\Cache]] for common cache operations that are supported by Cache.
  19. *
  20. * The following example shows how you can configure the application to use Cache:
  21. *
  22. * ```php
  23. * 'cache' => [
  24. * 'class' => 'yii\mongodb\Cache',
  25. * // 'db' => 'mymongodb',
  26. * // 'cacheCollection' => 'my_cache',
  27. * ]
  28. * ```
  29. *
  30. * @author Paul Klimov <klimov.paul@gmail.com>
  31. * @since 2.0
  32. */
  33. class Cache extends \yii\caching\Cache
  34. {
  35. /**
  36. * @var Connection|array|string the MongoDB connection object or the application component ID of the MongoDB connection.
  37. * After the Cache object is created, if you want to change this property, you should only assign it
  38. * with a MongoDB connection object.
  39. * Starting from version 2.0.2, this can also be a configuration array for creating the object.
  40. */
  41. public $db = 'mongodb';
  42. /**
  43. * @var string|array the name of the MongoDB collection that stores the cache data.
  44. * Please refer to [[Connection::getCollection()]] on how to specify this parameter.
  45. * This collection is better to be pre-created with fields 'id' and 'expire' indexed.
  46. */
  47. public $cacheCollection = 'cache';
  48. /**
  49. * @var int the probability (parts per million) that garbage collection (GC) should be performed
  50. * when storing a piece of data in the cache. Defaults to 100, meaning 0.01% chance.
  51. * This number should be between 0 and 1000000. A value 0 meaning no GC will be performed at all.
  52. */
  53. public $gcProbability = 100;
  54. /**
  55. * Initializes the Cache component.
  56. * This method will initialize the [[db]] property to make sure it refers to a valid MongoDB connection.
  57. * @throws InvalidConfigException if [[db]] is invalid.
  58. */
  59. public function init()
  60. {
  61. parent::init();
  62. $this->db = Instance::ensure($this->db, Connection::className());
  63. }
  64. /**
  65. * Retrieves a value from cache with a specified key.
  66. * This method should be implemented by child classes to retrieve the data
  67. * from specific cache storage.
  68. * @param string $key a unique key identifying the cached value
  69. * @return string|bool the value stored in cache, false if the value is not in the cache or expired.
  70. */
  71. protected function getValue($key)
  72. {
  73. $query = new Query;
  74. $row = $query->select(['data'])
  75. ->from($this->cacheCollection)
  76. ->where([
  77. 'id' => $key,
  78. '$or' => [
  79. [
  80. 'expire' => 0
  81. ],
  82. [
  83. 'expire' => ['$gt' => time()]
  84. ],
  85. ],
  86. ])
  87. ->one($this->db);
  88. if (empty($row)) {
  89. return false;
  90. }
  91. return $row['data'];
  92. }
  93. /**
  94. * Stores a value identified by a key in cache.
  95. * This method should be implemented by child classes to store the data
  96. * in specific cache storage.
  97. * @param string $key the key identifying the value to be cached
  98. * @param string $value the value to be cached
  99. * @param int $expire the number of seconds in which the cached value will expire. 0 means never expire.
  100. * @return bool true if the value is successfully stored into cache, false otherwise
  101. */
  102. protected function setValue($key, $value, $expire)
  103. {
  104. $result = $this->db->getCollection($this->cacheCollection)
  105. ->update(['id' => $key], [
  106. 'expire' => $expire > 0 ? $expire + time() : 0,
  107. 'data' => $value,
  108. ]);
  109. if ($result) {
  110. $this->gc();
  111. return true;
  112. }
  113. return $this->addValue($key, $value, $expire);
  114. }
  115. /**
  116. * Stores a value identified by a key into cache if the cache does not contain this key.
  117. * This method should be implemented by child classes to store the data
  118. * in specific cache storage.
  119. * @param string $key the key identifying the value to be cached
  120. * @param string $value the value to be cached
  121. * @param int $expire the number of seconds in which the cached value will expire. 0 means never expire.
  122. * @return bool true if the value is successfully stored into cache, false otherwise
  123. */
  124. protected function addValue($key, $value, $expire)
  125. {
  126. $this->gc();
  127. if ($expire > 0) {
  128. $expire += time();
  129. } else {
  130. $expire = 0;
  131. }
  132. try {
  133. $this->db->getCollection($this->cacheCollection)
  134. ->insert([
  135. 'id' => $key,
  136. 'expire' => $expire,
  137. 'data' => $value,
  138. ]);
  139. return true;
  140. } catch (\Exception $e) {
  141. return false;
  142. }
  143. }
  144. /**
  145. * Deletes a value with the specified key from cache
  146. * This method should be implemented by child classes to delete the data from actual cache storage.
  147. * @param string $key the key of the value to be deleted
  148. * @return bool if no error happens during deletion
  149. */
  150. protected function deleteValue($key)
  151. {
  152. $this->db->getCollection($this->cacheCollection)->remove(['id' => $key]);
  153. return true;
  154. }
  155. /**
  156. * Deletes all values from cache.
  157. * Child classes may implement this method to realize the flush operation.
  158. * @return bool whether the flush operation was successful.
  159. */
  160. protected function flushValues()
  161. {
  162. $this->db->getCollection($this->cacheCollection)->remove();
  163. return true;
  164. }
  165. /**
  166. * Removes the expired data values.
  167. * @param bool $force whether to enforce the garbage collection regardless of [[gcProbability]].
  168. * Defaults to false, meaning the actual deletion happens with the probability as specified by [[gcProbability]].
  169. */
  170. public function gc($force = false)
  171. {
  172. if ($force || mt_rand(0, 1000000) < $this->gcProbability) {
  173. $this->db->getCollection($this->cacheCollection)
  174. ->remove([
  175. 'expire' => [
  176. '$gt' => 0,
  177. '$lt' => time(),
  178. ]
  179. ]);
  180. }
  181. }
  182. }