3
* @link https://www.yiiframework.com/
4
* @copyright Copyright (c) 2008 Yii Software LLC
5
* @license https://www.yiiframework.com/license/
11
use yii\base\InvalidConfigException;
18
* DbCache implements a cache application component by storing cached data in a database.
20
* By default, DbCache stores session data in a DB table named 'cache'. This table
21
* must be pre-created. The table name can be changed by setting [[cacheTable]].
23
* Please refer to [[Cache]] for common cache operations that are supported by DbCache.
25
* The following example shows how you can configure the application to use DbCache:
29
* 'class' => 'yii\caching\DbCache',
31
* // 'cacheTable' => 'my_cache',
35
* For more details and usage information on Cache, see the [guide article on caching](guide:caching-overview).
37
* @author Qiang Xue <qiang.xue@gmail.com>
40
class DbCache extends Cache
43
* @var Connection|array|string the DB connection object or the application component ID of the DB connection.
44
* After the DbCache object is created, if you want to change this property, you should only assign it
45
* with a DB connection object.
46
* Starting from version 2.0.2, this can also be a configuration array for creating the object.
50
* @var string name of the DB table to store cache content.
51
* The table should be pre-created as follows:
54
* CREATE TABLE cache (
55
* id char(128) NOT NULL PRIMARY KEY,
63
* CREATE TABLE cache (
64
* id VARCHAR(128) NOT NULL PRIMARY KEY,
70
* where 'BLOB' refers to the BLOB-type of your preferred DBMS. Below are the BLOB type
71
* that can be used for some popular DBMS:
76
* When using DbCache in a production server, we recommend you create a DB index for the 'expire'
77
* column in the cache table to improve the performance.
79
public $cacheTable = '{{%cache}}';
81
* @var int the probability (parts per million) that garbage collection (GC) should be performed
82
* when storing a piece of data in the cache. Defaults to 100, meaning 0.01% chance.
83
* This number should be between 0 and 1000000. A value 0 meaning no GC will be performed at all.
85
public $gcProbability = 100;
87
protected $isVarbinaryDataField;
91
* Initializes the DbCache component.
92
* This method will initialize the [[db]] property to make sure it refers to a valid DB connection.
93
* @throws InvalidConfigException if [[db]] is invalid.
95
public function init()
98
$this->db = Instance::ensure($this->db, Connection::className());
102
* Checks whether a specified key exists in the cache.
103
* This can be faster than getting the value from the cache if the data is big.
104
* Note that this method does not check whether the dependency associated
105
* with the cached data, if there is any, has changed. So a call to [[get]]
106
* may return false while exists returns true.
107
* @param mixed $key a key identifying the cached value. This can be a simple string or
108
* a complex data structure consisting of factors representing the key.
109
* @return bool true if a value exists in cache, false if the value is not in the cache or expired.
111
public function exists($key)
113
$key = $this->buildKey($key);
115
$query = new Query();
116
$query->select(['COUNT(*)'])
117
->from($this->cacheTable)
118
->where('[[id]] = :id AND ([[expire]] = 0 OR [[expire]] >' . time() . ')', [':id' => $key]);
119
if ($this->db->enableQueryCache) {
120
// temporarily disable and re-enable query caching
121
$this->db->enableQueryCache = false;
122
$result = $query->createCommand($this->db)->queryScalar();
123
$this->db->enableQueryCache = true;
125
$result = $query->createCommand($this->db)->queryScalar();
132
* Retrieves a value from cache with a specified key.
133
* This is the implementation of the method declared in the parent class.
134
* @param string $key a unique key identifying the cached value
135
* @return string|false the value stored in cache, false if the value is not in the cache or expired.
137
protected function getValue($key)
139
$query = new Query();
140
$query->select([$this->getDataFieldName()])
141
->from($this->cacheTable)
142
->where('[[id]] = :id AND ([[expire]] = 0 OR [[expire]] >' . time() . ')', [':id' => $key]);
143
if ($this->db->enableQueryCache) {
144
// temporarily disable and re-enable query caching
145
$this->db->enableQueryCache = false;
146
$result = $query->createCommand($this->db)->queryScalar();
147
$this->db->enableQueryCache = true;
152
return $query->createCommand($this->db)->queryScalar();
156
* Retrieves multiple values from cache with the specified keys.
157
* @param array $keys a list of keys identifying the cached values
158
* @return array a list of cached values indexed by the keys
160
protected function getValues($keys)
165
$query = new Query();
166
$query->select(['id', $this->getDataFieldName()])
167
->from($this->cacheTable)
168
->where(['id' => $keys])
169
->andWhere('([[expire]] = 0 OR [[expire]] > ' . time() . ')');
171
if ($this->db->enableQueryCache) {
172
$this->db->enableQueryCache = false;
173
$rows = $query->createCommand($this->db)->queryAll();
174
$this->db->enableQueryCache = true;
176
$rows = $query->createCommand($this->db)->queryAll();
180
foreach ($keys as $key) {
181
$results[$key] = false;
183
foreach ($rows as $row) {
184
if (is_resource($row['data']) && get_resource_type($row['data']) === 'stream') {
185
$results[$row['id']] = stream_get_contents($row['data']);
187
$results[$row['id']] = $row['data'];
195
* Stores a value identified by a key in cache.
196
* This is the implementation of the method declared in the parent class.
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
203
protected function setValue($key, $value, $duration)
206
$this->db->noCache(function (Connection $db) use ($key, $value, $duration) {
207
$db->createCommand()->upsert($this->cacheTable, [
209
'expire' => $duration > 0 ? $duration + time() : 0,
210
'data' => $this->getDataFieldValue($value),
217
} catch (\Exception $e) {
218
Yii::warning("Unable to update or insert cache data: {$e->getMessage()}", __METHOD__);
225
* Stores a value identified by a key into cache if the cache does not contain this key.
226
* This is the implementation of the method declared in the parent class.
228
* @param string $key the key identifying the value to be cached
229
* @param string $value the value to be cached. Other types (if you have disabled [[serializer]]) cannot be saved.
230
* @param int $duration the number of seconds in which the cached value will expire. 0 means never expire.
231
* @return bool true if the value is successfully stored into cache, false otherwise
233
protected function addValue($key, $value, $duration)
238
$this->db->noCache(function (Connection $db) use ($key, $value, $duration) {
240
->insert($this->cacheTable, [
242
'expire' => $duration > 0 ? $duration + time() : 0,
243
'data' => $this->getDataFieldValue($value),
248
} catch (\Exception $e) {
249
Yii::warning("Unable to insert cache data: {$e->getMessage()}", __METHOD__);
256
* Deletes a value with the specified key from cache
257
* This is the implementation of the method declared in the parent class.
258
* @param string $key the key of the value to be deleted
259
* @return bool if no error happens during deletion
261
protected function deleteValue($key)
263
$this->db->noCache(function (Connection $db) use ($key) {
265
->delete($this->cacheTable, ['id' => $key])
273
* Removes the expired data values.
274
* @param bool $force whether to enforce the garbage collection regardless of [[gcProbability]].
275
* Defaults to false, meaning the actual deletion happens with the probability as specified by [[gcProbability]].
277
public function gc($force = false)
280
if ($force || random_int(0, 1000000) < $this->gcProbability) {
281
$this->db->createCommand()
282
->delete($this->cacheTable, '[[expire]] > 0 AND [[expire]] < ' . time())
288
* Deletes all values from cache.
289
* This is the implementation of the method declared in the parent class.
290
* @return bool whether the flush operation was successful.
292
protected function flushValues()
294
$this->db->createCommand()
295
->delete($this->cacheTable)
302
* @return bool whether field is MSSQL varbinary
305
protected function isVarbinaryDataField()
307
if ($this->isVarbinaryDataField === null) {
308
$this->isVarbinaryDataField = in_array($this->db->getDriverName(), ['sqlsrv', 'dblib']) &&
309
$this->db->getTableSchema($this->cacheTable)->columns['data']->dbType === 'varbinary';
311
return $this->isVarbinaryDataField;
315
* @return string `data` field name converted for usage in MSSQL (if needed)
318
protected function getDataFieldName()
320
return $this->isVarbinaryDataField() ? 'CONVERT(VARCHAR(MAX), [[data]]) data' : 'data';
324
* @return PdoValue PdoValue or direct $value for usage in MSSQL
327
protected function getDataFieldValue($value)
329
return $this->isVarbinaryDataField() ? $value : new PdoValue($value, \PDO::PARAM_LOB);