Yii2 framework backup
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.

261 lines
7.7 KiB

13 years ago
<?php
/**
12 years ago
* DbCache class file
13 years ago
*
* @link http://www.yiiframework.com/
* @copyright Copyright &copy; 2008-2012 Yii Software LLC
13 years ago
* @license http://www.yiiframework.com/license/
*/
namespace yii\caching;
12 years ago
use yii\base\Exception;
use yii\db\Connection;
use yii\db\Query;
13 years ago
/**
12 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 $dbConnection The DB connection instance.
13 years ago
*
* @author Qiang Xue <qiang.xue@gmail.com>
* @since 2.0
13 years ago
*/
12 years ago
class DbCache extends Cache
13 years ago
{
/**
12 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
*/
12 years ago
public $cacheTableName = 'tbl_cache';
13 years ago
/**
12 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 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
13 years ago
*/
private $_db;
/**
12 years ago
* 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.
13 years ago
*/
public function getDbConnection()
{
12 years ago
if ($this->_db === null) {
$db = \Yii::$application->getComponent($this->connectionID);
if ($db instanceof Connection) {
12 years ago
$this->_db = $db;
} else {
throw new Exception("DbCache.connectionID must refer to the ID of a DB connection application component.");
}
13 years ago
}
12 years ago
return $this->_db;
13 years ago
}
/**
* Sets the DB connection used by the cache component.
12 years ago
* @param Connection $value the DB connection instance
13 years ago
*/
public function setDbConnection($value)
{
12 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)
{
12 years ago
$query = new Query;
$query->select(array('data'))
12 years ago
->from($this->cacheTableName)
->where('id = :id AND (expire = 0 OR expire > :time)', array(':id' => $key, ':time' => time()));
12 years ago
$db = $this->getDbConnection();
if ($db->queryCachingDuration >= 0) {
12 years ago
// temporarily disable and re-enable query caching
12 years ago
$duration = $db->queryCachingDuration;
$db->queryCachingDuration = -1;
$result = $query->createCommand($db)->queryScalar();
$db->queryCachingDuration = $duration;
13 years ago
return $result;
12 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)
{
12 years ago
if (empty($keys)) {
13 years ago
return array();
12 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->getDbConnection();
if ($db->queryCachingDuration >= 0) {
12 years ago
$duration = $db->queryCachingDuration;
$db->queryCachingDuration = -1;
$rows = $query->createCommand($db)->queryAll();
12 years ago
$db->queryCachingDuration = $duration;
} else {
$rows = $query->createCommand($db)->queryAll();
13 years ago
}
12 years ago
$results = array();
foreach ($keys as $key) {
$results[$key] = false;
}
foreach ($rows as $row) {
$results[$row['id']] = $row['data'];
12 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
*/
12 years ago
protected function setValue($key, $value, $expire)
13 years ago
{
$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);
}
}
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
*/
12 years ago
protected function addValue($key, $value, $expire)
13 years ago
{
$this->gc();
13 years ago
12 years ago
if ($expire > 0) {
$expire += time();
} else {
$expire = 0;
}
$query = new Query;
$command = $query->insert($this->cacheTableName, array(
'id' => $key,
'expire' => $expire,
'data' => array($value, \PDO::PARAM_LOB),
))->createCommand($this->getDbConnection());
12 years ago
try {
13 years ago
$command->execute();
return true;
12 years ago
} 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)
{
$query = new Query;
$query->delete($this->cacheTableName, array('id' => $key))
->createCommand($this->getDbConnection())
->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) {
$query = new Query;
$query->delete($this->cacheTableName, 'expire > 0 AND expire < ' . time())
->createCommand($this->getDbConnection())
->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()
{
$query = new Query;
$query->delete($this->cacheTableName)
->createCommand($this->getDbConnection())
->execute();
13 years ago
return true;
}
}