DbCache.php 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287
  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\PdoValue;
  12. use yii\db\Query;
  13. use yii\di\Instance;
  14. /**
  15. * DbCache implements a cache application component by storing cached data in a database.
  16. *
  17. * By default, DbCache stores session data in a DB table named 'cache'. This table
  18. * must be pre-created. The table name can be changed by setting [[cacheTable]].
  19. *
  20. * Please refer to [[Cache]] for common cache operations that are supported by DbCache.
  21. *
  22. * The following example shows how you can configure the application to use DbCache:
  23. *
  24. * ```php
  25. * 'cache' => [
  26. * 'class' => 'yii\caching\DbCache',
  27. * // 'db' => 'mydb',
  28. * // 'cacheTable' => 'my_cache',
  29. * ]
  30. * ```
  31. *
  32. * For more details and usage information on Cache, see the [guide article on caching](guide:caching-overview).
  33. *
  34. * @author Qiang Xue <qiang.xue@gmail.com>
  35. * @since 2.0
  36. */
  37. class DbCache extends Cache
  38. {
  39. /**
  40. * @var Connection|array|string the DB connection object or the application component ID of the DB connection.
  41. * After the DbCache object is created, if you want to change this property, you should only assign it
  42. * with a DB connection object.
  43. * Starting from version 2.0.2, this can also be a configuration array for creating the object.
  44. */
  45. public $db = 'db';
  46. /**
  47. * @var string name of the DB table to store cache content.
  48. * The table should be pre-created as follows:
  49. *
  50. * ```php
  51. * CREATE TABLE cache (
  52. * id char(128) NOT NULL PRIMARY KEY,
  53. * expire int(11),
  54. * data BLOB
  55. * );
  56. * ```
  57. *
  58. * where 'BLOB' refers to the BLOB-type of your preferred DBMS. Below are the BLOB type
  59. * that can be used for some popular DBMS:
  60. *
  61. * - MySQL: LONGBLOB
  62. * - PostgreSQL: BYTEA
  63. * - MSSQL: BLOB
  64. *
  65. * When using DbCache in a production server, we recommend you create a DB index for the 'expire'
  66. * column in the cache table to improve the performance.
  67. */
  68. public $cacheTable = '{{%cache}}';
  69. /**
  70. * @var int the probability (parts per million) that garbage collection (GC) should be performed
  71. * when storing a piece of data in the cache. Defaults to 100, meaning 0.01% chance.
  72. * This number should be between 0 and 1000000. A value 0 meaning no GC will be performed at all.
  73. */
  74. public $gcProbability = 100;
  75. /**
  76. * Initializes the DbCache component.
  77. * This method will initialize the [[db]] property to make sure it refers to a valid DB connection.
  78. * @throws InvalidConfigException if [[db]] is invalid.
  79. */
  80. public function init()
  81. {
  82. parent::init();
  83. $this->db = Instance::ensure($this->db, Connection::className());
  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 bool 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|false 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. }
  131. return $query->createCommand($this->db)->queryScalar();
  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. if (is_resource($row['data']) && get_resource_type($row['data']) === 'stream') {
  161. $results[$row['id']] = stream_get_contents($row['data']);
  162. } else {
  163. $results[$row['id']] = $row['data'];
  164. }
  165. }
  166. return $results;
  167. }
  168. /**
  169. * Stores a value identified by a key in cache.
  170. * This is the implementation of the method declared in the parent class.
  171. *
  172. * @param string $key the key identifying the value to be cached
  173. * @param string $value the value to be cached. Other types (if you have disabled [[serializer]]) cannot be saved.
  174. * @param int $duration the number of seconds in which the cached value will expire. 0 means never expire.
  175. * @return bool true if the value is successfully stored into cache, false otherwise
  176. */
  177. protected function setValue($key, $value, $duration)
  178. {
  179. $result = $this->db->noCache(function (Connection $db) use ($key, $value, $duration) {
  180. $command = $db->createCommand()
  181. ->update($this->cacheTable, [
  182. 'expire' => $duration > 0 ? $duration + time() : 0,
  183. 'data' => new PdoValue($value, \PDO::PARAM_LOB),
  184. ], ['id' => $key]);
  185. return $command->execute();
  186. });
  187. if ($result) {
  188. $this->gc();
  189. return true;
  190. }
  191. return $this->addValue($key, $value, $duration);
  192. }
  193. /**
  194. * Stores a value identified by a key into cache if the cache does not contain this key.
  195. * This is the implementation of the method declared in the parent class.
  196. *
  197. * @param string $key the key identifying the value to be cached
  198. * @param string $value the value to be cached. Other types (if you have disabled [[serializer]]) cannot be saved.
  199. * @param int $duration the number of seconds in which the cached value will expire. 0 means never expire.
  200. * @return bool true if the value is successfully stored into cache, false otherwise
  201. */
  202. protected function addValue($key, $value, $duration)
  203. {
  204. $this->gc();
  205. try {
  206. $this->db->noCache(function (Connection $db) use ($key, $value, $duration) {
  207. $db->createCommand()
  208. ->insert($this->cacheTable, [
  209. 'id' => $key,
  210. 'expire' => $duration > 0 ? $duration + time() : 0,
  211. 'data' => new PdoValue($value, \PDO::PARAM_LOB),
  212. ])->execute();
  213. });
  214. return true;
  215. } catch (\Exception $e) {
  216. return false;
  217. }
  218. }
  219. /**
  220. * Deletes a value with the specified key from cache
  221. * This is the implementation of the method declared in the parent class.
  222. * @param string $key the key of the value to be deleted
  223. * @return bool if no error happens during deletion
  224. */
  225. protected function deleteValue($key)
  226. {
  227. $this->db->noCache(function (Connection $db) use ($key) {
  228. $db->createCommand()
  229. ->delete($this->cacheTable, ['id' => $key])
  230. ->execute();
  231. });
  232. return true;
  233. }
  234. /**
  235. * Removes the expired data values.
  236. * @param bool $force whether to enforce the garbage collection regardless of [[gcProbability]].
  237. * Defaults to false, meaning the actual deletion happens with the probability as specified by [[gcProbability]].
  238. */
  239. public function gc($force = false)
  240. {
  241. if ($force || mt_rand(0, 1000000) < $this->gcProbability) {
  242. $this->db->createCommand()
  243. ->delete($this->cacheTable, '[[expire]] > 0 AND [[expire]] < ' . time())
  244. ->execute();
  245. }
  246. }
  247. /**
  248. * Deletes all values from cache.
  249. * This is the implementation of the method declared in the parent class.
  250. * @return bool whether the flush operation was successful.
  251. */
  252. protected function flushValues()
  253. {
  254. $this->db->createCommand()
  255. ->delete($this->cacheTable)
  256. ->execute();
  257. return true;
  258. }
  259. }