DbCache.php 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290
  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. try {
  180. $this->db->noCache(function (Connection $db) use ($key, $value, $duration) {
  181. $db->createCommand()->upsert($this->cacheTable, [
  182. 'id' => $key,
  183. 'expire' => $duration > 0 ? $duration + time() : 0,
  184. 'data' => new PdoValue($value, \PDO::PARAM_LOB),
  185. ])->execute();
  186. });
  187. $this->gc();
  188. return true;
  189. } catch (\Exception $e) {
  190. Yii::warning("Unable to update or insert cache data: {$e->getMessage()}", __METHOD__);
  191. return false;
  192. }
  193. }
  194. /**
  195. * Stores a value identified by a key into cache if the cache does not contain this key.
  196. * This is the implementation of the method declared in the parent class.
  197. *
  198. * @param string $key the key identifying the value to be cached
  199. * @param string $value the value to be cached. Other types (if you have disabled [[serializer]]) cannot be saved.
  200. * @param int $duration the number of seconds in which the cached value will expire. 0 means never expire.
  201. * @return bool true if the value is successfully stored into cache, false otherwise
  202. */
  203. protected function addValue($key, $value, $duration)
  204. {
  205. $this->gc();
  206. try {
  207. $this->db->noCache(function (Connection $db) use ($key, $value, $duration) {
  208. $db->createCommand()
  209. ->insert($this->cacheTable, [
  210. 'id' => $key,
  211. 'expire' => $duration > 0 ? $duration + time() : 0,
  212. 'data' => new PdoValue($value, \PDO::PARAM_LOB),
  213. ])->execute();
  214. });
  215. return true;
  216. } catch (\Exception $e) {
  217. Yii::warning("Unable to insert cache data: {$e->getMessage()}", __METHOD__);
  218. return false;
  219. }
  220. }
  221. /**
  222. * Deletes a value with the specified key from cache
  223. * This is the implementation of the method declared in the parent class.
  224. * @param string $key the key of the value to be deleted
  225. * @return bool if no error happens during deletion
  226. */
  227. protected function deleteValue($key)
  228. {
  229. $this->db->noCache(function (Connection $db) use ($key) {
  230. $db->createCommand()
  231. ->delete($this->cacheTable, ['id' => $key])
  232. ->execute();
  233. });
  234. return true;
  235. }
  236. /**
  237. * Removes the expired data values.
  238. * @param bool $force whether to enforce the garbage collection regardless of [[gcProbability]].
  239. * Defaults to false, meaning the actual deletion happens with the probability as specified by [[gcProbability]].
  240. */
  241. public function gc($force = false)
  242. {
  243. if ($force || mt_rand(0, 1000000) < $this->gcProbability) {
  244. $this->db->createCommand()
  245. ->delete($this->cacheTable, '[[expire]] > 0 AND [[expire]] < ' . time())
  246. ->execute();
  247. }
  248. }
  249. /**
  250. * Deletes all values from cache.
  251. * This is the implementation of the method declared in the parent class.
  252. * @return bool whether the flush operation was successful.
  253. */
  254. protected function flushValues()
  255. {
  256. $this->db->createCommand()
  257. ->delete($this->cacheTable)
  258. ->execute();
  259. return true;
  260. }
  261. }