1: <?php
2: /**
3: * CCache 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: * CCache is the base class for cache classes with different cache storage implementation.
13: *
14: * A data item can be stored in cache by calling {@link set} and be retrieved back
15: * later by {@link get}. In both operations, a key identifying the data item is required.
16: * An expiration time and/or a dependency can also be specified when calling {@link set}.
17: * If the data item expires or the dependency changes, calling {@link get} will not
18: * return back the data item.
19: *
20: * Note, by definition, cache does not ensure the existence of a value
21: * even if it does not expire. Cache is not meant to be a persistent storage.
22: *
23: * CCache implements the interface {@link ICache} with the following methods:
24: * <ul>
25: * <li>{@link get} : retrieve the value with a key (if any) from cache</li>
26: * <li>{@link set} : store the value with a key into cache</li>
27: * <li>{@link add} : store the value only if cache does not have this key</li>
28: * <li>{@link delete} : delete the value with the specified key from cache</li>
29: * <li>{@link flush} : delete all values from cache</li>
30: * </ul>
31: *
32: * Child classes must implement the following methods:
33: * <ul>
34: * <li>{@link getValue}</li>
35: * <li>{@link setValue}</li>
36: * <li>{@link addValue}</li>
37: * <li>{@link deleteValue}</li>
38: * <li>{@link getValues} (optional)</li>
39: * <li>{@link flushValues} (optional)</li>
40: * <li>{@link serializer} (optional)</li>
41: * </ul>
42: *
43: * CCache also implements ArrayAccess so that it can be used like an array.
44: *
45: * @author Qiang Xue <qiang.xue@gmail.com>
46: * @package system.caching
47: * @since 1.0
48: */
49: abstract class CCache extends CApplicationComponent implements ICache, ArrayAccess
50: {
51: /**
52: * @var string a string prefixed to every cache key so that it is unique. Defaults to null which means
53: * to use the {@link CApplication::getId() application ID}. If different applications need to access the same
54: * pool of cached data, the same prefix should be set for each of the applications explicitly.
55: */
56: public $keyPrefix;
57: /**
58: * @var boolean whether to md5-hash the cache key for normalization purposes. Defaults to true. Setting this property to false makes sure the cache
59: * key will not be tampered when calling the relevant methods {@link get()}, {@link set()}, {@link add()} and {@link delete()}. This is useful if a Yii
60: * application as well as an external application need to access the same cache pool (also see description of {@link keyPrefix} regarding this use case).
61: * However, without normalization you should make sure the affected cache backend does support the structure (charset, length, etc.) of all the provided
62: * cache keys, otherwise there might be unexpected behavior.
63: * @since 1.1.11
64: **/
65: public $hashKey=true;
66: /**
67: * @var array|boolean the functions used to serialize and unserialize cached data. Defaults to null, meaning
68: * using the default PHP `serialize()` and `unserialize()` functions. If you want to use some more efficient
69: * serializer (e.g. {@link http://pecl.php.net/package/igbinary igbinary}), you may configure this property with
70: * a two-element array. The first element specifies the serialization function, and the second the deserialization
71: * function. If this property is set false, data will be directly sent to and retrieved from the underlying
72: * cache component without any serialization or deserialization. You should not turn off serialization if
73: * you are using {@link CCacheDependency cache dependency}, because it relies on data serialization.
74: */
75: public $serializer;
76:
77: /**
78: * Initializes the application component.
79: * This method overrides the parent implementation by setting default cache key prefix.
80: */
81: public function init()
82: {
83: parent::init();
84: if($this->keyPrefix===null)
85: $this->keyPrefix=Yii::app()->getId();
86: }
87:
88: /**
89: * @param string $key a key identifying a value to be cached
90: * @return string a key generated from the provided key which ensures the uniqueness across applications
91: */
92: protected function generateUniqueKey($key)
93: {
94: return $this->hashKey ? md5($this->keyPrefix.$key) : $this->keyPrefix.$key;
95: }
96:
97: /**
98: * Retrieves a value from cache with a specified key.
99: * @param string $id a key identifying the cached value
100: * @return mixed the value stored in cache, false if the value is not in the cache, expired or the dependency has changed.
101: */
102: public function get($id)
103: {
104: $value = $this->getValue($this->generateUniqueKey($id));
105: if($value===false || $this->serializer===false)
106: return $value;
107: if($this->serializer===null)
108: $value=unserialize($value);
109: else
110: $value=call_user_func($this->serializer[1], $value);
111: if(is_array($value) && (!$value[1] instanceof ICacheDependency || !$value[1]->getHasChanged()))
112: {
113: Yii::trace('Serving "'.$id.'" from cache','system.caching.'.get_class($this));
114: return $value[0];
115: }
116: else
117: return false;
118: }
119:
120: /**
121: * Retrieves multiple values from cache with the specified keys.
122: * Some caches (such as memcache, apc) allow retrieving multiple cached values at one time,
123: * which may improve the performance since it reduces the communication cost.
124: * In case a cache does not support this feature natively, it will be simulated by this method.
125: * @param array $ids list of keys identifying the cached values
126: * @return array list of cached values corresponding to the specified keys. The array
127: * is returned in terms of (key,value) pairs.
128: * If a value is not cached or expired, the corresponding array value will be false.
129: */
130: public function mget($ids)
131: {
132: $uids = array();
133: foreach ($ids as $id)
134: $uids[$id] = $this->generateUniqueKey($id);
135:
136: $values = $this->getValues($uids);
137: $results = array();
138: if($this->serializer === false)
139: {
140: foreach ($uids as $id => $uid)
141: $results[$id] = isset($values[$uid]) ? $values[$uid] : false;
142: }
143: else
144: {
145: foreach($uids as $id => $uid)
146: {
147: $results[$id] = false;
148: if(isset($values[$uid]))
149: {
150: $value = $this->serializer === null ? unserialize($values[$uid]) : call_user_func($this->serializer[1], $values[$uid]);
151: if(is_array($value) && (!$value[1] instanceof ICacheDependency || !$value[1]->getHasChanged()))
152: {
153: Yii::trace('Serving "'.$id.'" from cache','system.caching.'.get_class($this));
154: $results[$id] = $value[0];
155: }
156: }
157: }
158: }
159: return $results;
160: }
161:
162: /**
163: * Stores a value identified by a key into cache.
164: * If the cache already contains such a key, the existing value and
165: * expiration time will be replaced with the new ones.
166: *
167: * @param string $id the key identifying the value to be cached
168: * @param mixed $value the value to be cached
169: * @param integer $expire the number of seconds in which the cached value will expire. 0 means never expire.
170: * @param ICacheDependency $dependency dependency of the cached item. If the dependency changes, the item is labeled invalid.
171: * @return boolean true if the value is successfully stored into cache, false otherwise
172: */
173: public function set($id,$value,$expire=0,$dependency=null)
174: {
175: Yii::trace('Saving "'.$id.'" to cache','system.caching.'.get_class($this));
176:
177: if ($dependency !== null && $this->serializer !== false)
178: $dependency->evaluateDependency();
179:
180: if ($this->serializer === null)
181: $value = serialize(array($value,$dependency));
182: elseif ($this->serializer !== false)
183: $value = call_user_func($this->serializer[0], array($value,$dependency));
184:
185: return $this->setValue($this->generateUniqueKey($id), $value, $expire);
186: }
187:
188: /**
189: * Stores a value identified by a key into cache if the cache does not contain this key.
190: * Nothing will be done if the cache already contains the key.
191: * @param string $id the key identifying the value to be cached
192: * @param mixed $value the value to be cached
193: * @param integer $expire the number of seconds in which the cached value will expire. 0 means never expire.
194: * @param ICacheDependency $dependency dependency of the cached item. If the dependency changes, the item is labeled invalid.
195: * @return boolean true if the value is successfully stored into cache, false otherwise
196: */
197: public function add($id,$value,$expire=0,$dependency=null)
198: {
199: Yii::trace('Adding "'.$id.'" to cache','system.caching.'.get_class($this));
200:
201: if ($dependency !== null && $this->serializer !== false)
202: $dependency->evaluateDependency();
203:
204: if ($this->serializer === null)
205: $value = serialize(array($value,$dependency));
206: elseif ($this->serializer !== false)
207: $value = call_user_func($this->serializer[0], array($value,$dependency));
208:
209: return $this->addValue($this->generateUniqueKey($id), $value, $expire);
210: }
211:
212: /**
213: * Deletes a value with the specified key from cache
214: * @param string $id the key of the value to be deleted
215: * @return boolean if no error happens during deletion
216: */
217: public function delete($id)
218: {
219: Yii::trace('Deleting "'.$id.'" from cache','system.caching.'.get_class($this));
220: return $this->deleteValue($this->generateUniqueKey($id));
221: }
222:
223: /**
224: * Deletes all values from cache.
225: * Be careful of performing this operation if the cache is shared by multiple applications.
226: * @return boolean whether the flush operation was successful.
227: */
228: public function flush()
229: {
230: Yii::trace('Flushing cache','system.caching.'.get_class($this));
231: return $this->flushValues();
232: }
233:
234: /**
235: * Retrieves a value from cache with a specified key.
236: * This method should be implemented by child classes to retrieve the data
237: * from specific cache storage. The uniqueness and dependency are handled
238: * in {@link get()} already. So only the implementation of data retrieval
239: * is needed.
240: * @param string $key a unique key identifying the cached value
241: * @return string|boolean the value stored in cache, false if the value is not in the cache or expired.
242: * @throws CException if this method is not overridden by child classes
243: */
244: protected function getValue($key)
245: {
246: throw new CException(Yii::t('yii','{className} does not support get() functionality.',
247: array('{className}'=>get_class($this))));
248: }
249:
250: /**
251: * Retrieves multiple values from cache with the specified keys.
252: * The default implementation simply calls {@link getValue} multiple
253: * times to retrieve the cached values one by one.
254: * If the underlying cache storage supports multiget, this method should
255: * be overridden to exploit that feature.
256: * @param array $keys a list of keys identifying the cached values
257: * @return array a list of cached values indexed by the keys
258: */
259: protected function getValues($keys)
260: {
261: $results=array();
262: foreach($keys as $key)
263: $results[$key]=$this->getValue($key);
264: return $results;
265: }
266:
267: /**
268: * Stores a value identified by a key in cache.
269: * This method should be implemented by child classes to store the data
270: * in specific cache storage. The uniqueness and dependency are handled
271: * in {@link set()} already. So only the implementation of data storage
272: * is needed.
273: *
274: * @param string $key the key identifying the value to be cached
275: * @param string $value the value to be cached
276: * @param integer $expire the number of seconds in which the cached value will expire. 0 means never expire.
277: * @return boolean true if the value is successfully stored into cache, false otherwise
278: * @throws CException if this method is not overridden by child classes
279: */
280: protected function setValue($key,$value,$expire)
281: {
282: throw new CException(Yii::t('yii','{className} does not support set() functionality.',
283: array('{className}'=>get_class($this))));
284: }
285:
286: /**
287: * Stores a value identified by a key into cache if the cache does not contain this key.
288: * This method should be implemented by child classes to store the data
289: * in specific cache storage. The uniqueness and dependency are handled
290: * in {@link add()} already. So only the implementation of data storage
291: * is needed.
292: *
293: * @param string $key the key identifying the value to be cached
294: * @param string $value the value to be cached
295: * @param integer $expire the number of seconds in which the cached value will expire. 0 means never expire.
296: * @return boolean true if the value is successfully stored into cache, false otherwise
297: * @throws CException if this method is not overridden by child classes
298: */
299: protected function addValue($key,$value,$expire)
300: {
301: throw new CException(Yii::t('yii','{className} does not support add() functionality.',
302: array('{className}'=>get_class($this))));
303: }
304:
305: /**
306: * Deletes a value with the specified key from cache
307: * This method should be implemented by child classes to delete the data from actual cache storage.
308: * @param string $key the key of the value to be deleted
309: * @return boolean if no error happens during deletion
310: * @throws CException if this method is not overridden by child classes
311: */
312: protected function deleteValue($key)
313: {
314: throw new CException(Yii::t('yii','{className} does not support delete() functionality.',
315: array('{className}'=>get_class($this))));
316: }
317:
318: /**
319: * Deletes all values from cache.
320: * Child classes may implement this method to realize the flush operation.
321: * @return boolean whether the flush operation was successful.
322: * @throws CException if this method is not overridden by child classes
323: * @since 1.1.5
324: */
325: protected function flushValues()
326: {
327: throw new CException(Yii::t('yii','{className} does not support flushValues() functionality.',
328: array('{className}'=>get_class($this))));
329: }
330:
331: /**
332: * Returns whether there is a cache entry with a specified key.
333: * This method is required by the interface ArrayAccess.
334: * @param string $id a key identifying the cached value
335: * @return boolean
336: */
337: public function offsetExists($id)
338: {
339: return $this->get($id)!==false;
340: }
341:
342: /**
343: * Retrieves the value from cache with a specified key.
344: * This method is required by the interface ArrayAccess.
345: * @param string $id a key identifying the cached value
346: * @return mixed the value stored in cache, false if the value is not in the cache or expired.
347: */
348: public function offsetGet($id)
349: {
350: return $this->get($id);
351: }
352:
353: /**
354: * Stores the value identified by a key into cache.
355: * If the cache already contains such a key, the existing value will be
356: * replaced with the new ones. To add expiration and dependencies, use the set() method.
357: * This method is required by the interface ArrayAccess.
358: * @param string $id the key identifying the value to be cached
359: * @param mixed $value the value to be cached
360: */
361: public function offsetSet($id, $value)
362: {
363: $this->set($id, $value);
364: }
365:
366: /**
367: * Deletes the value with the specified key from cache
368: * This method is required by the interface ArrayAccess.
369: * @param string $id the key of the value to be deleted
370: * @return boolean if no error happens during deletion
371: */
372: public function offsetUnset($id)
373: {
374: $this->delete($id);
375: }
376: }