Yii2 Bootstrap 3
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

253 lines
7.4 KiB

13 years ago
<?php
/**
13 years ago
* DbCache class file
13 years ago
*
* @link http://www.yiiframework.com/
* @copyright Copyright &copy; 2008 Yii Software LLC
13 years ago
* @license http://www.yiiframework.com/license/
*/
namespace yii\caching;
use yii\base\InvalidConfigException;
use yii\db\Connection;
use yii\db\Query;
13 years ago
/**
13 years ago
* DbCache implements a cache application component by storing cached data in a database.
13 years ago
*
* 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 :
13 years ago
*
* ~~~
* CREATE TABLE tbl_cache (
* id char(128) NOT NULL,
* expire int(11) DEFAULT NULL,
* data LONGBLOB,
* PRIMARY KEY (id),
* KEY expire (expire)
* );
* ~~~
13 years ago
*
* 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.
13 years ago
*
12 years ago
* @property Connection $db The DB connection instance.
13 years ago
*
* @author Qiang Xue <qiang.xue@gmail.com>
* @since 2.0
13 years ago
*/
13 years ago
class DbCache extends Cache
13 years ago
{
/**
13 years ago
* @var string the ID of the [[Connection|DB connection]] application component. Defaults to 'db'.
13 years ago
*/
public $connectionID = 'db';
13 years ago
/**
* @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.
13 years ago
*/
13 years ago
public $cacheTableName = 'tbl_cache';
13 years ago
/**
13 years ago
* @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 10, meaning 0.001% chance.
13 years ago
* 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
13 years ago
*/
private $_db;
/**
13 years ago
* Returns the DB connection instance used for caching purpose.
* @return Connection the DB connection instance
* @throws InvalidConfigException if [[connectionID]] does not point to a valid application component.
13 years ago
*/
12 years ago
public function getDb()
13 years ago
{
13 years ago
if ($this->_db === null) {
$db = \Yii::$app->getComponent($this->connectionID);
if ($db instanceof Connection) {
13 years ago
$this->_db = $db;
} else {
throw new InvalidConfigException("DbCache::connectionID must refer to the ID of a DB application component.");
13 years ago
}
13 years ago
}
13 years ago
return $this->_db;
13 years ago
}
/**
* Sets the DB connection used by the cache component.
13 years ago
* @param Connection $value the DB connection instance
13 years ago
*/
12 years ago
public function setDb($value)
13 years ago
{
13 years ago
$this->_db = $value;
13 years ago
}
/**
* 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)
{
13 years ago
$query = new Query;
$query->select(array('data'))
13 years ago
->from($this->cacheTableName)
->where('id = :id AND (expire = 0 OR expire >' . time() . ')', array(':id' => $key));
12 years ago
$db = $this->getDb();
if ($db->enableQueryCache) {
13 years ago
// temporarily disable and re-enable query caching
$db->enableQueryCache = false;
13 years ago
$result = $query->createCommand($db)->queryScalar();
$db->enableQueryCache = true;
13 years ago
return $result;
13 years ago
} else {
return $query->createCommand($db)->queryScalar();
13 years ago
}
}
/**
* 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)
{
13 years ago
if (empty($keys)) {
13 years ago
return array();
13 years ago
}
$query = new Query;
$query->select(array('id', 'data'))
->from($this->cacheTableName)
->where(array('id' => $keys))
->andWhere('(expire = 0 OR expire > ' . time() . ')');
13 years ago
12 years ago
$db = $this->getDb();
if ($db->enableQueryCache) {
$db->enableQueryCache = false;
$rows = $query->createCommand($db)->queryAll();
$db->enableQueryCache = true;
13 years ago
} else {
$rows = $query->createCommand($db)->queryAll();
13 years ago
}
13 years ago
$results = array();
foreach ($keys as $key) {
$results[$key] = false;
}
foreach ($rows as $row) {
$results[$row['id']] = $row['data'];
13 years ago
}
13 years ago
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
*/
13 years ago
protected function setValue($key, $value, $expire)
13 years ago
{
$command = $this->getDb()->createCommand();
$command->update($this->cacheTableName, array(
'expire' => $expire > 0 ? $expire + time() : 0,
'data' => array($value, \PDO::PARAM_LOB),
), array(
'id' => $key,
));;
if ($command->execute()) {
$this->gc();
return true;
} else {
return $this->addValue($key, $value, $expire);
}
}
13 years ago
/**
* 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
*/
13 years ago
protected function addValue($key, $value, $expire)
13 years ago
{
$this->gc();
13 years ago
13 years ago
if ($expire > 0) {
$expire += time();
} else {
$expire = 0;
}
$command = $this->getDb()->createCommand();
$command->insert($this->cacheTableName, array(
'id' => $key,
'expire' => $expire,
'data' => array($value, \PDO::PARAM_LOB),
));
13 years ago
try {
13 years ago
$command->execute();
return true;
} catch (\Exception $e) {
13 years ago
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)
{
$command = $this->getDb()->createCommand();
$command->delete($this->cacheTableName, array('id' => $key))->execute();
13 years ago
return true;
}
/**
* Removes the expired data values.
* @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]].
13 years ago
*/
public function gc($force = false)
13 years ago
{
if ($force || mt_rand(0, 1000000) < $this->gcProbability) {
$command = $this->getDb()->createCommand();
$command->delete($this->cacheTableName, 'expire > 0 AND expire < ' . time())->execute();
}
13 years ago
}
/**
* 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()
{
$command = $this->getDb()->createCommand();
$command->delete($this->cacheTableName)->execute();
13 years ago
return true;
}
}