DbCache.php 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274
  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\caching;
  8. use Yii;
  9. use yii\base\InvalidConfigException;
  10. use yii\db\Connection;
  11. use yii\db\Query;
  12. /**
  13. * DbCache implements a cache application component by storing cached data in a database.
  14. *
  15. * By default, DbCache stores session data in a DB table named 'tbl_cache'. This table
  16. * must be pre-created. The table name can be changed by setting [[cacheTable]].
  17. *
  18. * Please refer to [[Cache]] for common cache operations that are supported by DbCache.
  19. *
  20. * The following example shows how you can configure the application to use DbCache:
  21. *
  22. * ~~~
  23. * 'cache' => [
  24. * 'class' => 'yii\caching\DbCache',
  25. * // 'db' => 'mydb',
  26. * // 'cacheTable' => 'my_cache',
  27. * ]
  28. * ~~~
  29. *
  30. * @author Qiang Xue <[email protected]>
  31. * @since 2.0
  32. */
  33. class DbCache extends Cache
  34. {
  35. /**
  36. * @var Connection|string the DB connection object or the application component ID of the DB connection.
  37. * After the DbCache object is created, if you want to change this property, you should only assign it
  38. * with a DB connection object.
  39. */
  40. public $db = 'db';
  41. /**
  42. * @var string name of the DB table to store cache content.
  43. * The table should be pre-created as follows:
  44. *
  45. * ~~~
  46. * CREATE TABLE tbl_cache (
  47. * id char(128) NOT NULL PRIMARY KEY,
  48. * expire int(11),
  49. * data BLOB
  50. * );
  51. * ~~~
  52. *
  53. * where 'BLOB' refers to the BLOB-type of your preferred DBMS. Below are the BLOB type
  54. * that can be used for some popular DBMS:
  55. *
  56. * - MySQL: LONGBLOB
  57. * - PostgreSQL: BYTEA
  58. * - MSSQL: BLOB
  59. *
  60. * When using DbCache in a production server, we recommend you create a DB index for the 'expire'
  61. * column in the cache table to improve the performance.
  62. */
  63. public $cacheTable = '{{%cache}}';
  64. /**
  65. * @var integer the probability (parts per million) that garbage collection (GC) should be performed
  66. * when storing a piece of data in the cache. Defaults to 100, meaning 0.01% chance.
  67. * This number should be between 0 and 1000000. A value 0 meaning no GC will be performed at all.
  68. **/
  69. public $gcProbability = 100;
  70. /**
  71. * Initializes the DbCache component.
  72. * This method will initialize the [[db]] property to make sure it refers to a valid DB connection.
  73. * @throws InvalidConfigException if [[db]] is invalid.
  74. */
  75. public function init()
  76. {
  77. parent::init();
  78. if (is_string($this->db)) {
  79. $this->db = Yii::$app->getComponent($this->db);
  80. }
  81. if (!$this->db instanceof Connection) {
  82. throw new InvalidConfigException("DbCache::db must be either a DB connection instance or the application component ID of a DB connection.");
  83. }
  84. }
  85. /**
  86. * Checks whether a specified key exists in the cache.
  87. * This can be faster than getting the value from the cache if the data is big.
  88. * Note that this method does not check whether the dependency associated
  89. * with the cached data, if there is any, has changed. So a call to [[get]]
  90. * may return false while exists returns true.
  91. * @param mixed $key a key identifying the cached value. This can be a simple string or
  92. * a complex data structure consisting of factors representing the key.
  93. * @return boolean true if a value exists in cache, false if the value is not in the cache or expired.
  94. */
  95. public function exists($key)
  96. {
  97. $key = $this->buildKey($key);
  98. $query = new Query;
  99. $query->select(['COUNT(*)'])
  100. ->from($this->cacheTable)
  101. ->where('[[id]] = :id AND ([[expire]] = 0 OR [[expire]] >' . time() . ')', [':id' => $key]);
  102. if ($this->db->enableQueryCache) {
  103. // temporarily disable and re-enable query caching
  104. $this->db->enableQueryCache = false;
  105. $result = $query->createCommand($this->db)->queryScalar();
  106. $this->db->enableQueryCache = true;
  107. } else {
  108. $result = $query->createCommand($this->db)->queryScalar();
  109. }
  110. return $result > 0;
  111. }
  112. /**
  113. * Retrieves a value from cache with a specified key.
  114. * This is the implementation of the method declared in the parent class.
  115. * @param string $key a unique key identifying the cached value
  116. * @return string|boolean the value stored in cache, false if the value is not in the cache or expired.
  117. */
  118. protected function getValue($key)
  119. {
  120. $query = new Query;
  121. $query->select(['data'])
  122. ->from($this->cacheTable)
  123. ->where('[[id]] = :id AND ([[expire]] = 0 OR [[expire]] >' . time() . ')', [':id' => $key]);
  124. if ($this->db->enableQueryCache) {
  125. // temporarily disable and re-enable query caching
  126. $this->db->enableQueryCache = false;
  127. $result = $query->createCommand($this->db)->queryScalar();
  128. $this->db->enableQueryCache = true;
  129. return $result;
  130. } else {
  131. return $query->createCommand($this->db)->queryScalar();
  132. }
  133. }
  134. /**
  135. * Retrieves multiple values from cache with the specified keys.
  136. * @param array $keys a list of keys identifying the cached values
  137. * @return array a list of cached values indexed by the keys
  138. */
  139. protected function getValues($keys)
  140. {
  141. if (empty($keys)) {
  142. return [];
  143. }
  144. $query = new Query;
  145. $query->select(['id', 'data'])
  146. ->from($this->cacheTable)
  147. ->where(['id' => $keys])
  148. ->andWhere('([[expire]] = 0 OR [[expire]] > ' . time() . ')');
  149. if ($this->db->enableQueryCache) {
  150. $this->db->enableQueryCache = false;
  151. $rows = $query->createCommand($this->db)->queryAll();
  152. $this->db->enableQueryCache = true;
  153. } else {
  154. $rows = $query->createCommand($this->db)->queryAll();
  155. }
  156. $results = [];
  157. foreach ($keys as $key) {
  158. $results[$key] = false;
  159. }
  160. foreach ($rows as $row) {
  161. $results[$row['id']] = $row['data'];
  162. }
  163. return $results;
  164. }
  165. /**
  166. * Stores a value identified by a key in cache.
  167. * This is the implementation of the method declared in the parent class.
  168. *
  169. * @param string $key the key identifying the value to be cached
  170. * @param string $value the value to be cached
  171. * @param integer $expire the number of seconds in which the cached value will expire. 0 means never expire.
  172. * @return boolean true if the value is successfully stored into cache, false otherwise
  173. */
  174. protected function setValue($key, $value, $expire)
  175. {
  176. $command = $this->db->createCommand()
  177. ->update($this->cacheTable, [
  178. 'expire' => $expire > 0 ? $expire + time() : 0,
  179. 'data' => [$value, \PDO::PARAM_LOB],
  180. ], ['id' => $key]);
  181. if ($command->execute()) {
  182. $this->gc();
  183. return true;
  184. } else {
  185. return $this->addValue($key, $value, $expire);
  186. }
  187. }
  188. /**
  189. * Stores a value identified by a key into cache if the cache does not contain this key.
  190. * This is the implementation of the method declared in the parent class.
  191. *
  192. * @param string $key the key identifying the value to be cached
  193. * @param string $value the value to be cached
  194. * @param integer $expire the number of seconds in which the cached value will expire. 0 means never expire.
  195. * @return boolean true if the value is successfully stored into cache, false otherwise
  196. */
  197. protected function addValue($key, $value, $expire)
  198. {
  199. $this->gc();
  200. if ($expire > 0) {
  201. $expire += time();
  202. } else {
  203. $expire = 0;
  204. }
  205. try {
  206. $this->db->createCommand()
  207. ->insert($this->cacheTable, [
  208. 'id' => $key,
  209. 'expire' => $expire,
  210. 'data' => [$value, \PDO::PARAM_LOB],
  211. ])->execute();
  212. return true;
  213. } catch (\Exception $e) {
  214. return false;
  215. }
  216. }
  217. /**
  218. * Deletes a value with the specified key from cache
  219. * This is the implementation of the method declared in the parent class.
  220. * @param string $key the key of the value to be deleted
  221. * @return boolean if no error happens during deletion
  222. */
  223. protected function deleteValue($key)
  224. {
  225. $this->db->createCommand()
  226. ->delete($this->cacheTable, ['id' => $key])
  227. ->execute();
  228. return true;
  229. }
  230. /**
  231. * Removes the expired data values.
  232. * @param boolean $force whether to enforce the garbage collection regardless of [[gcProbability]].
  233. * Defaults to false, meaning the actual deletion happens with the probability as specified by [[gcProbability]].
  234. */
  235. public function gc($force = false)
  236. {
  237. if ($force || mt_rand(0, 1000000) < $this->gcProbability) {
  238. $this->db->createCommand()
  239. ->delete($this->cacheTable, '[[expire]] > 0 AND [[expire]] < ' . time())
  240. ->execute();
  241. }
  242. }
  243. /**
  244. * Deletes all values from cache.
  245. * This is the implementation of the method declared in the parent class.
  246. * @return boolean whether the flush operation was successful.
  247. */
  248. protected function flushValues()
  249. {
  250. $this->db->createCommand()
  251. ->delete($this->cacheTable)
  252. ->execute();
  253. return true;
  254. }
  255. }