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