DbCache.php 7.39 KB
Newer Older
Qiang Xue committed
1 2
<?php
/**
Qiang Xue committed
3
 * DbCache class file
Qiang Xue committed
4 5
 *
 * @link http://www.yiiframework.com/
Qiang Xue committed
6
 * @copyright Copyright &copy; 2008 Yii Software LLC
Qiang Xue committed
7 8 9
 * @license http://www.yiiframework.com/license/
 */

Qiang Xue committed
10 11
namespace yii\caching;

12
use yii\base\InvalidConfigException;
Qiang Xue committed
13 14
use yii\db\Connection;
use yii\db\Query;
Qiang Xue committed
15

Qiang Xue committed
16
/**
Qiang Xue committed
17
 * DbCache implements a cache application component by storing cached data in a database.
Qiang Xue committed
18
 *
19 20
 * DbCache stores cache data in a DB table whose name is specified via [[cacheTableName]].
 * For MySQL database, the table should be created beforehand as follows :
Qiang Xue committed
21
 *
22 23
 * ~~~
 * CREATE TABLE tbl_cache (
24 25 26 27 28
 *     id char(128) NOT NULL,
 *     expire int(11) DEFAULT NULL,
 *     data LONGBLOB,
 *     PRIMARY KEY (id),
 *     KEY expire (expire)
29 30
 * );
 * ~~~
Qiang Xue committed
31
 *
32 33 34 35 36 37 38 39 40
 * You should replace `LONGBLOB` as follows if you are using a different DBMS:
 *
 * - PostgreSQL: `BYTEA`
 * - SQLite, SQL server, Oracle: `BLOB`
 *
 * DbCache connects to the database via the DB connection specified in [[connectionID]]
 * which must refer to a valid DB application component.
 *
 * Please refer to [[Cache]] for common cache operations that are supported by DbCache.
Qiang Xue committed
41
 *
Qiang Xue committed
42
 * @property Connection $db The DB connection instance.
Qiang Xue committed
43 44
 *
 * @author Qiang Xue <qiang.xue@gmail.com>
Qiang Xue committed
45
 * @since 2.0
Qiang Xue committed
46
 */
Qiang Xue committed
47
class DbCache extends Cache
Qiang Xue committed
48 49
{
	/**
Qiang Xue committed
50
	 * @var string the ID of the [[Connection|DB connection]] application component. Defaults to 'db'.
Qiang Xue committed
51
	 */
52
	public $connectionID = 'db';
Qiang Xue committed
53
	/**
54 55
	 * @var string name of the DB table to store cache content. Defaults to 'tbl_cache'.
	 * The table must be created before using this cache component.
Qiang Xue committed
56
	 */
Qiang Xue committed
57
	public $cacheTableName = 'tbl_cache';
Qiang Xue committed
58
	/**
Qiang Xue committed
59
	 * @var integer the probability (parts per million) that garbage collection (GC) should be performed
60
	 * when storing a piece of data in the cache. Defaults to 10, meaning 0.001% chance.
Qiang Xue committed
61 62 63 64 65
	 * This number should be between 0 and 1000000. A value 0 meaning no GC will be performed at all.
	 **/
	public $gcProbability = 100;
	/**
	 * @var Connection the DB connection instance
Qiang Xue committed
66 67 68 69
	 */
	private $_db;

	/**
Qiang Xue committed
70 71
	 * Returns the DB connection instance used for caching purpose.
	 * @return Connection the DB connection instance
72
	 * @throws InvalidConfigException if [[connectionID]] does not point to a valid application component.
Qiang Xue committed
73
	 */
Qiang Xue committed
74
	public function getDb()
Qiang Xue committed
75
	{
Qiang Xue committed
76
		if ($this->_db === null) {
Qiang Xue committed
77
			$db = \Yii::$app->getComponent($this->connectionID);
78
			if ($db instanceof Connection) {
Qiang Xue committed
79 80
				$this->_db = $db;
			} else {
81
				throw new InvalidConfigException("DbCache::connectionID must refer to the ID of a DB application component.");
Qiang Xue committed
82
			}
Qiang Xue committed
83
		}
Qiang Xue committed
84
		return $this->_db;
Qiang Xue committed
85 86 87 88
	}

	/**
	 * Sets the DB connection used by the cache component.
Qiang Xue committed
89
	 * @param Connection $value the DB connection instance
Qiang Xue committed
90
	 */
Qiang Xue committed
91
	public function setDb($value)
Qiang Xue committed
92
	{
Qiang Xue committed
93
		$this->_db = $value;
Qiang Xue committed
94 95 96 97 98 99 100 101 102 103
	}

	/**
	 * Retrieves a value from cache with a specified key.
	 * This is the implementation of the method declared in the parent class.
	 * @param string $key a unique key identifying the cached value
	 * @return string the value stored in cache, false if the value is not in the cache or expired.
	 */
	protected function getValue($key)
	{
Qiang Xue committed
104
		$query = new Query;
105
		$query->select(array('data'))
Qiang Xue committed
106
			->from($this->cacheTableName)
107
			->where('id = :id AND (expire = 0 OR expire >' . time() . ')', array(':id' => $key));
Qiang Xue committed
108
		$db = $this->getDb();
109
		if ($db->enableQueryCache) {
Qiang Xue committed
110
			// temporarily disable and re-enable query caching
111
			$db->enableQueryCache = false;
Qiang Xue committed
112
			$result = $query->createCommand($db)->queryScalar();
113
			$db->enableQueryCache = true;
Qiang Xue committed
114
			return $result;
Qiang Xue committed
115 116
		} else {
			return $query->createCommand($db)->queryScalar();
Qiang Xue committed
117 118 119 120 121 122 123 124 125 126
		}
	}

	/**
	 * Retrieves multiple values from cache with the specified keys.
	 * @param array $keys a list of keys identifying the cached values
	 * @return array a list of cached values indexed by the keys
	 */
	protected function getValues($keys)
	{
Qiang Xue committed
127
		if (empty($keys)) {
Qiang Xue committed
128
			return array();
Qiang Xue committed
129
		}
130 131 132 133
		$query = new Query;
		$query->select(array('id', 'data'))
			->from($this->cacheTableName)
			->where(array('id' => $keys))
134
			->andWhere('(expire = 0 OR expire > ' . time() . ')');
Qiang Xue committed
135

Qiang Xue committed
136
		$db = $this->getDb();
137 138
		if ($db->enableQueryCache) {
			$db->enableQueryCache = false;
139
			$rows = $query->createCommand($db)->queryAll();
140
			$db->enableQueryCache = true;
Qiang Xue committed
141
		} else {
142
			$rows = $query->createCommand($db)->queryAll();
Qiang Xue committed
143 144
		}

Qiang Xue committed
145 146 147 148 149
		$results = array();
		foreach ($keys as $key) {
			$results[$key] = false;
		}
		foreach ($rows as $row) {
150
			$results[$row['id']] = $row['data'];
Qiang Xue committed
151
		}
Qiang Xue committed
152 153 154 155 156 157 158 159 160 161 162 163
		return $results;
	}

	/**
	 * Stores a value identified by a key in cache.
	 * This is the implementation of the method declared in the parent class.
	 *
	 * @param string $key the key identifying the value to be cached
	 * @param string $value the value to be cached
	 * @param integer $expire the number of seconds in which the cached value will expire. 0 means never expire.
	 * @return boolean true if the value is successfully stored into cache, false otherwise
	 */
Qiang Xue committed
164
	protected function setValue($key, $value, $expire)
Qiang Xue committed
165
	{
166 167
		$command = $this->getDb()->createCommand();
		$command->update($this->cacheTableName, array(
168 169 170 171
			'expire' => $expire > 0 ? $expire + time() : 0,
			'data' => array($value, \PDO::PARAM_LOB),
		), array(
			'id' => $key,
172
		));;
173 174 175 176 177 178 179 180

		if ($command->execute()) {
			$this->gc();
			return true;
		} else {
			return $this->addValue($key, $value, $expire);
		}
 	}
Qiang Xue committed
181 182 183 184 185 186 187 188 189 190

	/**
	 * Stores a value identified by a key into cache if the cache does not contain this key.
	 * This is the implementation of the method declared in the parent class.
	 *
	 * @param string $key the key identifying the value to be cached
	 * @param string $value the value to be cached
	 * @param integer $expire the number of seconds in which the cached value will expire. 0 means never expire.
	 * @return boolean true if the value is successfully stored into cache, false otherwise
	 */
Qiang Xue committed
191
	protected function addValue($key, $value, $expire)
Qiang Xue committed
192
	{
193
		$this->gc();
Qiang Xue committed
194

Qiang Xue committed
195 196 197 198 199
		if ($expire > 0) {
			$expire += time();
		} else {
			$expire = 0;
		}
200

201 202
		$command = $this->getDb()->createCommand();
		$command->insert($this->cacheTableName, array(
203 204 205
			'id' => $key,
			'expire' => $expire,
			'data' => array($value, \PDO::PARAM_LOB),
206
		));
Qiang Xue committed
207
		try {
Qiang Xue committed
208 209
			$command->execute();
			return true;
210
		} catch (\Exception $e) {
Qiang Xue committed
211 212 213 214 215 216 217 218 219 220 221 222
			return false;
		}
	}

	/**
	 * Deletes a value with the specified key from cache
	 * This is the implementation of the method declared in the parent class.
	 * @param string $key the key of the value to be deleted
	 * @return boolean if no error happens during deletion
	 */
	protected function deleteValue($key)
	{
223 224
		$command = $this->getDb()->createCommand();
		$command->delete($this->cacheTableName, array('id' => $key))->execute();
Qiang Xue committed
225 226 227 228 229
		return true;
	}

	/**
	 * Removes the expired data values.
230 231
	 * @param boolean $force whether to enforce the garbage collection regardless of [[gcProbability]].
	 * Defaults to false, meaning the actual deletion happens with the probability as specified by [[gcProbability]].
Qiang Xue committed
232
	 */
233
	public function gc($force = false)
Qiang Xue committed
234
	{
235
		if ($force || mt_rand(0, 1000000) < $this->gcProbability) {
236 237
			$command = $this->getDb()->createCommand();
			$command->delete($this->cacheTableName, 'expire > 0 AND expire < ' . time())->execute();
238
		}
Qiang Xue committed
239 240 241 242 243 244 245 246 247
	}

	/**
	 * Deletes all values from cache.
	 * This is the implementation of the method declared in the parent class.
	 * @return boolean whether the flush operation was successful.
	 */
	protected function flushValues()
	{
248 249
		$command = $this->getDb()->createCommand();
		$command->delete($this->cacheTableName)->execute();
Qiang Xue committed
250 251 252
		return true;
	}
}