DbCache.php 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279
  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. }
  130. return $query->createCommand($this->db)->queryScalar();
  131. }
  132. /**
  133. * Retrieves multiple values from cache with the specified keys.
  134. * @param array $keys a list of keys identifying the cached values
  135. * @return array a list of cached values indexed by the keys
  136. */
  137. protected function getValues($keys)
  138. {
  139. if (empty($keys)) {
  140. return [];
  141. }
  142. $query = new Query;
  143. $query->select(['id', 'data'])
  144. ->from($this->cacheTable)
  145. ->where(['id' => $keys])
  146. ->andWhere('([[expire]] = 0 OR [[expire]] > ' . time() . ')');
  147. if ($this->db->enableQueryCache) {
  148. $this->db->enableQueryCache = false;
  149. $rows = $query->createCommand($this->db)->queryAll();
  150. $this->db->enableQueryCache = true;
  151. } else {
  152. $rows = $query->createCommand($this->db)->queryAll();
  153. }
  154. $results = [];
  155. foreach ($keys as $key) {
  156. $results[$key] = false;
  157. }
  158. foreach ($rows as $row) {
  159. $results[$row['id']] = $row['data'];
  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. Other types (if you have disabled [[serializer]]) cannot be saved.
  169. * @param int $duration the number of seconds in which the cached value will expire. 0 means never expire.
  170. * @return bool true if the value is successfully stored into cache, false otherwise
  171. */
  172. protected function setValue($key, $value, $duration)
  173. {
  174. $result = $this->db->noCache(function (Connection $db) use ($key, $value, $duration) {
  175. $command = $db->createCommand()
  176. ->update($this->cacheTable, [
  177. 'expire' => $duration > 0 ? $duration + time() : 0,
  178. 'data' => [$value, \PDO::PARAM_LOB],
  179. ], ['id' => $key]);
  180. return $command->execute();
  181. });
  182. if ($result) {
  183. $this->gc();
  184. return true;
  185. }
  186. return $this->addValue($key, $value, $duration);
  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. Other types (if you have disabled [[serializer]]) cannot be saved.
  194. * @param int $duration the number of seconds in which the cached value will expire. 0 means never expire.
  195. * @return bool true if the value is successfully stored into cache, false otherwise
  196. */
  197. protected function addValue($key, $value, $duration)
  198. {
  199. $this->gc();
  200. try {
  201. $this->db->noCache(function (Connection $db) use ($key, $value, $duration) {
  202. $db->createCommand()
  203. ->insert($this->cacheTable, [
  204. 'id' => $key,
  205. 'expire' => $duration > 0 ? $duration + time() : 0,
  206. 'data' => [$value, \PDO::PARAM_LOB],
  207. ])->execute();
  208. });
  209. return true;
  210. } catch (\Exception $e) {
  211. return false;
  212. }
  213. }
  214. /**
  215. * Deletes a value with the specified key from cache
  216. * This is the implementation of the method declared in the parent class.
  217. * @param string $key the key of the value to be deleted
  218. * @return bool if no error happens during deletion
  219. */
  220. protected function deleteValue($key)
  221. {
  222. $this->db->noCache(function (Connection $db) use ($key) {
  223. $db->createCommand()
  224. ->delete($this->cacheTable, ['id' => $key])
  225. ->execute();
  226. });
  227. return true;
  228. }
  229. /**
  230. * Removes the expired data values.
  231. * @param bool $force whether to enforce the garbage collection regardless of [[gcProbability]].
  232. * Defaults to false, meaning the actual deletion happens with the probability as specified by [[gcProbability]].
  233. */
  234. public function gc($force = false)
  235. {
  236. if ($force || mt_rand(0, 1000000) < $this->gcProbability) {
  237. $this->db->createCommand()
  238. ->delete($this->cacheTable, '[[expire]] > 0 AND [[expire]] < ' . time())
  239. ->execute();
  240. }
  241. }
  242. /**
  243. * Deletes all values from cache.
  244. * This is the implementation of the method declared in the parent class.
  245. * @return bool whether the flush operation was successful.
  246. */
  247. protected function flushValues()
  248. {
  249. $this->db->createCommand()
  250. ->delete($this->cacheTable)
  251. ->execute();
  252. return true;
  253. }
  254. }