1: <?php
2: /**
3: * CDbCache class file
4: *
5: * @author Qiang Xue <qiang.xue@gmail.com>
6: * @link http://www.yiiframework.com/
7: * @copyright 2008-2013 Yii Software LLC
8: * @license http://www.yiiframework.com/license/
9: */
10:
11: /**
12: * CDbCache implements a cache application component by storing cached data in a database.
13: *
14: * CDbCache stores cache data in a DB table named {@link cacheTableName}.
15: * If the table does not exist, it will be automatically created.
16: * By setting {@link autoCreateCacheTable} to false, you can also manually create the DB table.
17: *
18: * CDbCache relies on {@link http://www.php.net/manual/en/ref.pdo.php PDO} to access database.
19: * By default, it will use a SQLite3 database under the application runtime directory.
20: * You can also specify {@link connectionID} so that it makes use of
21: * a DB application component to access database.
22: *
23: * See {@link CCache} manual for common cache operations that are supported by CDbCache.
24: *
25: * @property integer $gCProbability The probability (parts per million) that garbage collection (GC) should be performed
26: * when storing a piece of data in the cache. Defaults to 100, meaning 0.01% chance.
27: * @property CDbConnection $dbConnection The DB connection instance.
28: *
29: * @author Qiang Xue <qiang.xue@gmail.com>
30: * @package system.caching
31: * @since 1.0
32: */
33: class CDbCache extends CCache
34: {
35: /**
36: * @var string the ID of the {@link CDbConnection} application component. If not set,
37: * a SQLite3 database will be automatically created and used. The SQLite database file
38: * is <code>protected/runtime/cache-YiiVersion.db</code>.
39: */
40: public $connectionID;
41: /**
42: * @var string name of the DB table to store cache content. Defaults to 'YiiCache'.
43: * Note, if {@link autoCreateCacheTable} is false and you want to create the DB table
44: * manually by yourself, you need to make sure the DB table is of the following structure:
45: * <pre>
46: * (id CHAR(128) PRIMARY KEY, expire INTEGER, value BLOB)
47: * </pre>
48: * Note, some DBMS might not support BLOB type. In this case, replace 'BLOB' with a suitable
49: * binary data type (e.g. LONGBLOB in MySQL, BYTEA in PostgreSQL.)
50: * @see autoCreateCacheTable
51: */
52: public $cacheTableName='YiiCache';
53: /**
54: * @var boolean whether the cache DB table should be created automatically if it does not exist. Defaults to true.
55: * If you already have the table created, it is recommended you set this property to be false to improve performance.
56: * @see cacheTableName
57: */
58: public $autoCreateCacheTable=true;
59: /**
60: * @var CDbConnection the DB connection instance
61: */
62: private $_db;
63: private $_gcProbability=100;
64: private $_gced=false;
65:
66: /**
67: * Initializes this application component.
68: *
69: * This method is required by the {@link IApplicationComponent} interface.
70: * It ensures the existence of the cache DB table.
71: * It also removes expired data items from the cache.
72: */
73: public function init()
74: {
75: parent::init();
76:
77: $db=$this->getDbConnection();
78: $db->setActive(true);
79: if($this->autoCreateCacheTable)
80: {
81: $sql="DELETE FROM {$this->cacheTableName} WHERE expire>0 AND expire<".time();
82: try
83: {
84: $db->createCommand($sql)->execute();
85: }
86: catch(Exception $e)
87: {
88: $this->createCacheTable($db,$this->cacheTableName);
89: }
90: }
91: }
92:
93: /**
94: * @return integer the probability (parts per million) that garbage collection (GC) should be performed
95: * when storing a piece of data in the cache. Defaults to 100, meaning 0.01% chance.
96: */
97: public function getGCProbability()
98: {
99: return $this->_gcProbability;
100: }
101:
102: /**
103: * @param integer $value the probability (parts per million) that garbage collection (GC) should be performed
104: * when storing a piece of data in the cache. Defaults to 100, meaning 0.01% chance.
105: * This number should be between 0 and 1000000. A value 0 meaning no GC will be performed at all.
106: */
107: public function setGCProbability($value)
108: {
109: $value=(int)$value;
110: if($value<0)
111: $value=0;
112: if($value>1000000)
113: $value=1000000;
114: $this->_gcProbability=$value;
115: }
116:
117: /**
118: * Creates the cache DB table.
119: * @param CDbConnection $db the database connection
120: * @param string $tableName the name of the table to be created
121: */
122: protected function createCacheTable($db,$tableName)
123: {
124: $driver=$db->getDriverName();
125: if($driver==='mysql')
126: $blob='LONGBLOB';
127: elseif($driver==='pgsql')
128: $blob='BYTEA';
129: else
130: $blob='BLOB';
131: $sql=<<<EOD
132: CREATE TABLE $tableName
133: (
134: id CHAR(128) PRIMARY KEY,
135: expire INTEGER,
136: value $blob
137: )
138: EOD;
139: $db->createCommand($sql)->execute();
140: }
141:
142: /**
143: * @return CDbConnection the DB connection instance
144: * @throws CException if {@link connectionID} does not point to a valid application component.
145: */
146: public function getDbConnection()
147: {
148: if($this->_db!==null)
149: return $this->_db;
150: elseif(($id=$this->connectionID)!==null)
151: {
152: if(($this->_db=Yii::app()->getComponent($id)) instanceof CDbConnection)
153: return $this->_db;
154: else
155: throw new CException(Yii::t('yii','CDbCache.connectionID "{id}" is invalid. Please make sure it refers to the ID of a CDbConnection application component.',
156: array('{id}'=>$id)));
157: }
158: else
159: {
160: $dbFile=Yii::app()->getRuntimePath().DIRECTORY_SEPARATOR.'cache-'.Yii::getVersion().'.db';
161: return $this->_db=new CDbConnection('sqlite:'.$dbFile);
162: }
163: }
164:
165: /**
166: * Sets the DB connection used by the cache component.
167: * @param CDbConnection $value the DB connection instance
168: * @since 1.1.5
169: */
170: public function setDbConnection($value)
171: {
172: $this->_db=$value;
173: }
174:
175: /**
176: * Retrieves a value from cache with a specified key.
177: * This is the implementation of the method declared in the parent class.
178: * @param string $key a unique key identifying the cached value
179: * @return string|boolean the value stored in cache, false if the value is not in the cache or expired.
180: */
181: protected function getValue($key)
182: {
183: $time=time();
184: $sql="SELECT value FROM {$this->cacheTableName} WHERE id='$key' AND (expire=0 OR expire>$time)";
185: $db=$this->getDbConnection();
186: if($db->queryCachingDuration>0)
187: {
188: $duration=$db->queryCachingDuration;
189: $db->queryCachingDuration=0;
190: $result=$db->createCommand($sql)->queryScalar();
191: $db->queryCachingDuration=$duration;
192: return $result;
193: }
194: else
195: return $db->createCommand($sql)->queryScalar();
196: }
197:
198: /**
199: * Retrieves multiple values from cache with the specified keys.
200: * @param array $keys a list of keys identifying the cached values
201: * @return array a list of cached values indexed by the keys
202: */
203: protected function getValues($keys)
204: {
205: if(empty($keys))
206: return array();
207:
208: $ids=implode("','",$keys);
209: $time=time();
210: $sql="SELECT id, value FROM {$this->cacheTableName} WHERE id IN ('$ids') AND (expire=0 OR expire>$time)";
211:
212: $db=$this->getDbConnection();
213: if($db->queryCachingDuration>0)
214: {
215: $duration=$db->queryCachingDuration;
216: $db->queryCachingDuration=0;
217: $rows=$db->createCommand($sql)->queryAll();
218: $db->queryCachingDuration=$duration;
219: }
220: else
221: $rows=$db->createCommand($sql)->queryAll();
222:
223: $results=array();
224: foreach($keys as $key)
225: $results[$key]=false;
226: foreach($rows as $row)
227: $results[$row['id']]=$row['value'];
228: return $results;
229: }
230:
231: /**
232: * Stores a value identified by a key in cache.
233: * This is the implementation of the method declared in the parent class.
234: *
235: * @param string $key the key identifying the value to be cached
236: * @param string $value the value to be cached
237: * @param integer $expire the number of seconds in which the cached value will expire. 0 means never expire.
238: * @return boolean true if the value is successfully stored into cache, false otherwise
239: */
240: protected function setValue($key,$value,$expire)
241: {
242: $this->deleteValue($key);
243: return $this->addValue($key,$value,$expire);
244: }
245:
246: /**
247: * Stores a value identified by a key into cache if the cache does not contain this key.
248: * This is the implementation of the method declared in the parent class.
249: *
250: * @param string $key the key identifying the value to be cached
251: * @param string $value the value to be cached
252: * @param integer $expire the number of seconds in which the cached value will expire. 0 means never expire.
253: * @return boolean true if the value is successfully stored into cache, false otherwise
254: */
255: protected function addValue($key,$value,$expire)
256: {
257: if(!$this->_gced && mt_rand(0,1000000)<$this->_gcProbability)
258: {
259: $this->gc();
260: $this->_gced=true;
261: }
262:
263: if($expire>0)
264: $expire+=time();
265: else
266: $expire=0;
267: $sql="INSERT INTO {$this->cacheTableName} (id,expire,value) VALUES ('$key',$expire,:value)";
268: try
269: {
270: $command=$this->getDbConnection()->createCommand($sql);
271: $command->bindValue(':value',$value,PDO::PARAM_LOB);
272: $command->execute();
273: return true;
274: }
275: catch(Exception $e)
276: {
277: return false;
278: }
279: }
280:
281: /**
282: * Deletes a value with the specified key from cache
283: * This is the implementation of the method declared in the parent class.
284: * @param string $key the key of the value to be deleted
285: * @return boolean if no error happens during deletion
286: */
287: protected function deleteValue($key)
288: {
289: $sql="DELETE FROM {$this->cacheTableName} WHERE id='$key'";
290: $this->getDbConnection()->createCommand($sql)->execute();
291: return true;
292: }
293:
294: /**
295: * Removes the expired data values.
296: */
297: protected function gc()
298: {
299: $this->getDbConnection()->createCommand("DELETE FROM {$this->cacheTableName} WHERE expire>0 AND expire<".time())->execute();
300: }
301:
302: /**
303: * Deletes all values from cache.
304: * This is the implementation of the method declared in the parent class.
305: * @return boolean whether the flush operation was successful.
306: * @since 1.1.5
307: */
308: protected function flushValues()
309: {
310: $this->getDbConnection()->createCommand("DELETE FROM {$this->cacheTableName}")->execute();
311: return true;
312: }
313: }
314: