Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

273 lines
9.3KB

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