DbCache.php 7.67 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-2012 Yii Software LLC
Qiang Xue committed
7 8 9
 * @license http://www.yiiframework.com/license/
 */

Qiang Xue committed
10 11
namespace yii\caching;

Qiang Xue committed
12 13 14
use yii\base\Exception;
use yii\db\dao\Connection;
use yii\db\dao\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 24 25 26 27 28 29 30
 * ~~~
 * CREATE TABLE tbl_cache (
 *   id char(128) NOT NULL,
 *   expire int(11) DEFAULT NULL,
 *   data LONGBLOB,
 *   PRIMARY KEY (id),
 *   KEY expire (expire)
 * );
 * ~~~
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 $dbConnection 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 60 61 62 63 64 65
	 * @var integer the probability (parts per million) that garbage collection (GC) should be performed
	 * when storing a piece of data in the cache. Defaults to 100, meaning 0.01% chance.
	 * 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 72
	 * Returns the DB connection instance used for caching purpose.
	 * @return Connection the DB connection instance
	 * @throws Exception if [[connectionID]] does not point to a valid application component.
Qiang Xue committed
73 74 75
	 */
	public function getDbConnection()
	{
Qiang Xue committed
76
		if ($this->_db === null) {
77 78
			$db = \Yii::$application->getComponent($this->connectionID);
			if ($db instanceof Connection) {
Qiang Xue committed
79 80 81 82
				$this->_db = $db;
			} else {
				throw new Exception("DbCache.connectionID must refer to the ID of a DB connection application component.");
			}
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 91 92
	 */
	public function setDbConnection($value)
	{
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, ':time' => time()));
Qiang Xue committed
108 109
		$db = $this->getDbConnection();
		if ($db->queryCachingDuration >= 0) {
Qiang Xue committed
110
			// temporarily disable and re-enable query caching
Qiang Xue committed
111 112 113 114
			$duration = $db->queryCachingDuration;
			$db->queryCachingDuration = -1;
			$result = $query->createCommand($db)->queryScalar();
			$db->queryCachingDuration = $duration;
Qiang Xue committed
115
			return $result;
Qiang Xue committed
116 117
		} else {
			return $query->createCommand($db)->queryScalar();
Qiang Xue committed
118 119 120 121 122 123 124 125 126 127
		}
	}

	/**
	 * 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
128
		if (empty($keys)) {
Qiang Xue committed
129
			return array();
Qiang Xue committed
130
		}
131 132 133 134 135
		$query = new Query;
		$query->select(array('id', 'data'))
			->from($this->cacheTableName)
			->where(array('id' => $keys))
			->andWhere("expire = 0 OR expire > " . time() . ")");
Qiang Xue committed
136

Qiang Xue committed
137
		$db = $this->getDbConnection();
138
		if ($db->queryCachingDuration >= 0) {
Qiang Xue committed
139
			$duration = $db->queryCachingDuration;
140 141
			$db->queryCachingDuration = -1;
			$rows = $query->createCommand($db)->queryAll();
Qiang Xue committed
142 143
			$db->queryCachingDuration = $duration;
		} else {
144
			$rows = $query->createCommand($db)->queryAll();
Qiang Xue committed
145 146
		}

Qiang Xue committed
147 148 149 150 151
		$results = array();
		foreach ($keys as $key) {
			$results[$key] = false;
		}
		foreach ($rows as $row) {
152
			$results[$row['id']] = $row['data'];
Qiang Xue committed
153
		}
Qiang Xue committed
154 155 156 157 158 159 160 161 162 163 164 165
		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
166
	protected function setValue($key, $value, $expire)
Qiang Xue committed
167
	{
168 169 170 171 172 173 174 175 176 177 178 179 180 181 182
		$query = new Query;
		$command = $query->update($this->cacheTableName, array(
			'expire' => $expire > 0 ? $expire + time() : 0,
			'data' => array($value, \PDO::PARAM_LOB),
		), array(
			'id' => $key,
		))->createCommand($this->getDbConnection());

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

	/**
	 * 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
193
	protected function addValue($key, $value, $expire)
Qiang Xue committed
194
	{
195
		$this->gc();
Qiang Xue committed
196

Qiang Xue committed
197 198 199 200 201
		if ($expire > 0) {
			$expire += time();
		} else {
			$expire = 0;
		}
202 203 204 205 206 207 208

		$query = new Query;
		$command = $query->insert($this->cacheTableName, array(
			'id' => $key,
			'expire' => $expire,
			'data' => array($value, \PDO::PARAM_LOB),
		))->createCommand($this->getDbConnection());
Qiang Xue committed
209
		try {
Qiang Xue committed
210 211
			$command->execute();
			return true;
Qiang Xue committed
212
		} catch (Exception $e) {
Qiang Xue committed
213 214 215 216 217 218 219 220 221 222 223 224
			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)
	{
225 226 227 228
		$query = new Query;
		$query->delete($this->cacheTableName, array('id' => $key))
			->createCommand($this->getDbConnection())
			->execute();
Qiang Xue committed
229 230 231 232 233
		return true;
	}

	/**
	 * Removes the expired data values.
234 235
	 * @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
236
	 */
237
	public function gc($force = false)
Qiang Xue committed
238
	{
239 240 241 242 243 244
		if ($force || mt_rand(0, 1000000) < $this->gcProbability) {
			$query = new Query;
			$query->delete($this->cacheTableName, 'expire > 0 AND expire < ' . time())
				->createCommand($this->getDbConnection())
				->execute();
		}
Qiang Xue committed
245 246 247 248 249 250 251 252 253
	}

	/**
	 * 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()
	{
254 255 256 257
		$query = new Query;
		$query->delete($this->cacheTableName)
			->createCommand($this->getDbConnection())
			->execute();
Qiang Xue committed
258 259 260
		return true;
	}
}