Cache.php 12.6 KB
Newer Older
Qiang Xue committed
1 2
<?php
/**
Qiang Xue committed
3
 * Cache class file.
Qiang Xue committed
4 5
 *
 * @link http://www.yiiframework.com/
Qiang Xue committed
6
 * @copyright Copyright &copy; 2008 Yii Software LLC
Qiang Xue committed
7 8 9
 * @license http://www.yiiframework.com/license/
 */

Qiang Xue committed
10 11
namespace yii\caching;

12
use yii\base\Component;
Qiang Xue committed
13

Qiang Xue committed
14
/**
Qiang Xue committed
15
 * Cache is the base class for cache classes supporting different cache storage implementation.
Qiang Xue committed
16
 *
Qiang Xue committed
17 18
 * A data item can be stored in cache by calling [[set()]] and be retrieved back
 * later (in the same or different request) by [[get()]]. In both operations,
Qiang Xue committed
19
 * a key identifying the data item is required. An expiration time and/or a [[Dependency|dependency]]
Qiang Xue committed
20 21
 * can also be specified when calling [[set()]]. If the data item expires or the dependency
 * changes at the time of calling [[get()]], the cache will return no data.
Qiang Xue committed
22
 *
23
 * A typical usage pattern of cache is like the following:
Qiang Xue committed
24
 *
25 26 27 28 29 30 31 32
 * ~~~
 * $key = 'demo';
 * $data = $cache->get($key);
 * if ($data === false) {
 *     // ...generate $data here...
 *     $cache->set($key, $data, $expire, $dependency);
 * }
 * ~~~
Qiang Xue committed
33
 *
Qiang Xue committed
34
 * Because Cache implements the ArrayAccess interface, it can be used like an array. For example,
Qiang Xue committed
35
 *
Qiang Xue committed
36 37 38 39
 * ~~~
 * $cache['foo'] = 'some data';
 * echo $cache['foo'];
 * ~~~
Qiang Xue committed
40
 *
41 42 43 44 45 46 47 48 49
 * Derived classes should implement the following methods:
 *
 * - [[getValue()]]: retrieve the value with a key (if any) from cache
 * - [[setValue()]]: store the value with a key into cache
 * - [[addValue()]]: store the value only if the cache does not have this key before
 * - [[deleteValue()]]: delete the value with the specified key from cache
 * - [[flushValues()]]: delete all values from cache
 *
 *
Qiang Xue committed
50
 * @author Qiang Xue <qiang.xue@gmail.com>
Qiang Xue committed
51
 * @since 2.0
Qiang Xue committed
52
 */
53
abstract class Cache extends Component implements \ArrayAccess
Qiang Xue committed
54 55
{
	/**
Qiang Xue committed
56 57 58 59
	 * @var string a string prefixed to every cache key so that it is unique. Defaults to null, meaning using
	 * the value of [[Application::id]] as the key prefix. You may set this property to be an empty string
	 * if you don't want to use key prefix. It is recommended that you explicitly set this property to some
	 * static value if the cached data needs to be shared among multiple applications.
Qiang Xue committed
60 61 62
	 */
	public $keyPrefix;
	/**
Qiang Xue committed
63 64 65 66 67 68
	 * @var array|boolean the functions used to serialize and unserialize cached data. Defaults to null, meaning
	 * using the default PHP `serialize()` and `unserialize()` functions. If you want to use some more efficient
	 * serializer (e.g. [igbinary](http://pecl.php.net/package/igbinary)), you may configure this property with
	 * a two-element array. The first element specifies the serialization function, and the second the deserialization
	 * function. If this property is set false, data will be directly sent to and retrieved from the underlying
	 * cache component without any serialization or deserialization. You should not turn off serialization if
Qiang Xue committed
69
	 * you are using [[Dependency|cache dependency]], because it relies on data serialization.
Qiang Xue committed
70
	 */
Qiang Xue committed
71
	public $serializer;
Qiang Xue committed
72

Qiang Xue committed
73 74

	/**
75 76 77 78 79 80 81 82 83
	 * Builds a normalized cache key from one or multiple parameters.
	 *
	 * The generated key contains letters and digits only, and its length is no more than 32.
	 * 
	 * If only one parameter is given and it is already a normalized key, then
	 * it will be returned back without change. Otherwise, a normalized key
	 * is generated by serializing all given parameters and applying MD5 hashing. 
	 * 
	 * The following example builds a cache key using three parameters:
Qiang Xue committed
84 85
	 *
	 * ~~~
Qiang Xue committed
86
	 * $key = $cache->buildKey($className, $method, $id);
Qiang Xue committed
87 88
	 * ~~~
	 *
89 90
	 * @param string $key the first parameter
	 * @return string the generated cache key
Qiang Xue committed
91
	 */
92
	public function buildKey($key)
Qiang Xue committed
93
	{
94 95
		if (func_num_args() === 1 && ctype_alnum($key) && strlen($key) <= 32) {
			return (string)$key;
Qiang Xue committed
96 97
		} else {
			$params = func_get_args();
98
			return md5(serialize($params));
Qiang Xue committed
99 100 101
		}
	}

Qiang Xue committed
102 103
	/**
	 * Retrieves a value from cache with a specified key.
104
	 * @param string $key a key identifying the cached value
Qiang Xue committed
105 106
	 * @return mixed the value stored in cache, false if the value is not in the cache, expired,
	 * or the dependency associated with the cached data has changed.
Qiang Xue committed
107
	 */
108
	public function get($key)
Qiang Xue committed
109
	{
110 111
		$key = $this->keyPrefix . $this->buildKey($key);
		$value = $this->getValue($key);
Qiang Xue committed
112 113 114 115 116 117 118
		if ($value === false || $this->serializer === false) {
			return $value;
		} elseif ($this->serializer === null) {
			$value = unserialize($value);
		} else {
			$value = call_user_func($this->serializer[1], $value);
		}
119
		if (is_array($value) && !($value[1] instanceof Dependency && $value[1]->getHasChanged())) {
Qiang Xue committed
120 121 122
			return $value[0];
		} else {
			return false;
Qiang Xue committed
123 124 125 126 127
		}
	}

	/**
	 * Retrieves multiple values from cache with the specified keys.
Qiang Xue committed
128 129 130
	 * Some caches (such as memcache, apc) allow retrieving multiple cached values at the same time,
	 * which may improve the performance. In case a cache does not support this feature natively,
	 * this method will try to simulate it.
131
	 * @param array $keys list of keys identifying the cached values
Qiang Xue committed
132 133 134 135
	 * @return array list of cached values corresponding to the specified keys. The array
	 * is returned in terms of (key,value) pairs.
	 * If a value is not cached or expired, the corresponding array value will be false.
	 */
136
	public function mget($keys)
Qiang Xue committed
137
	{
138 139 140
		$keyMap = array();
		foreach ($keys as $key) {
			$keyMap[$key] = $this->keyPrefix . $this->buildKey($key);
Qiang Xue committed
141
		}
142
		$values = $this->getValues(array_values($keyMap));
Qiang Xue committed
143
		$results = array();
144 145 146 147 148 149 150 151 152 153 154
		foreach ($keyMap as $key => $newKey) {
			$results[$key] = false;
			if (isset($values[$newKey])) {
				if ($this->serializer === false) {
					$results[$key] = $values[$newKey];
				} else {
					$value = $this->serializer === null ? unserialize($values[$newKey])
							: call_user_func($this->serializer[1], $values[$newKey]);

					if (is_array($value) && !($value[1] instanceof Dependency && $value[1]->getHasChanged())) {
						$results[$key] = $value[0];
Qiang Xue committed
155 156
					}
				}
Qiang Xue committed
157 158 159 160 161 162 163 164
			}
		}
		return $results;
	}

	/**
	 * Stores a value identified by a key into cache.
	 * If the cache already contains such a key, the existing value and
Qiang Xue committed
165
	 * expiration time will be replaced with the new ones, respectively.
Qiang Xue committed
166
	 *
167
	 * @param string $key the key identifying the value to be cached
Qiang Xue committed
168 169
	 * @param mixed $value the value to be cached
	 * @param integer $expire the number of seconds in which the cached value will expire. 0 means never expire.
Qiang Xue committed
170
	 * @param Dependency $dependency dependency of the cached item. If the dependency changes,
Qiang Xue committed
171
	 * the corresponding value in the cache will be invalidated when it is fetched via [[get()]].
172
	 * This parameter is ignored if [[serializer]] is false.
Qiang Xue committed
173
	 * @return boolean whether the value is successfully stored into cache
Qiang Xue committed
174
	 */
175
	public function set($key, $value, $expire = 0, $dependency = null)
Qiang Xue committed
176
	{
Qiang Xue committed
177
		if ($dependency !== null && $this->serializer !== false) {
Qiang Xue committed
178
			$dependency->evaluateDependency();
Qiang Xue committed
179
		}
Qiang Xue committed
180
		if ($this->serializer === null) {
Qiang Xue committed
181
			$value = serialize(array($value, $dependency));
Qiang Xue committed
182
		} elseif ($this->serializer !== false) {
Qiang Xue committed
183
			$value = call_user_func($this->serializer[0], array($value, $dependency));
Qiang Xue committed
184
		}
185 186
		$key = $this->keyPrefix . $this->buildKey($key);
		return $this->setValue($key, $value, $expire);
Qiang Xue committed
187 188 189 190 191
	}

	/**
	 * Stores a value identified by a key into cache if the cache does not contain this key.
	 * Nothing will be done if the cache already contains the key.
192
	 * @param string $key the key identifying the value to be cached
Qiang Xue committed
193 194
	 * @param mixed $value the value to be cached
	 * @param integer $expire the number of seconds in which the cached value will expire. 0 means never expire.
Qiang Xue committed
195
	 * @param Dependency $dependency dependency of the cached item. If the dependency changes,
Qiang Xue committed
196
	 * the corresponding value in the cache will be invalidated when it is fetched via [[get()]].
197
	 * This parameter is ignored if [[serializer]] is false.
Qiang Xue committed
198
	 * @return boolean whether the value is successfully stored into cache
Qiang Xue committed
199
	 */
200
	public function add($key, $value, $expire = 0, $dependency = null)
Qiang Xue committed
201
	{
Qiang Xue committed
202
		if ($dependency !== null && $this->serializer !== false) {
Qiang Xue committed
203
			$dependency->evaluateDependency();
Qiang Xue committed
204
		}
Qiang Xue committed
205
		if ($this->serializer === null) {
Qiang Xue committed
206
			$value = serialize(array($value, $dependency));
Qiang Xue committed
207
		} elseif ($this->serializer !== false) {
Qiang Xue committed
208
			$value = call_user_func($this->serializer[0], array($value, $dependency));
Qiang Xue committed
209
		}
210 211
		$key = $this->keyPrefix . $this->buildKey($key);
		return $this->addValue($key, $value, $expire);
Qiang Xue committed
212 213 214 215
	}

	/**
	 * Deletes a value with the specified key from cache
216
	 * @param string $key the key of the value to be deleted
Qiang Xue committed
217 218
	 * @return boolean if no error happens during deletion
	 */
219
	public function delete($key)
Qiang Xue committed
220
	{
221 222
		$key = $this->keyPrefix . $this->buildKey($key);
		return $this->deleteValue($key);
Qiang Xue committed
223 224 225 226
	}

	/**
	 * Deletes all values from cache.
Qiang Xue committed
227
	 * Be careful of performing this operation if the cache is shared among multiple applications.
Qiang Xue committed
228 229 230 231 232 233 234 235 236 237
	 * @return boolean whether the flush operation was successful.
	 */
	public function flush()
	{
		return $this->flushValues();
	}

	/**
	 * Retrieves a value from cache with a specified key.
	 * This method should be implemented by child classes to retrieve the data
Qiang Xue committed
238
	 * from specific cache storage.
Qiang Xue committed
239 240 241
	 * @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.
	 */
Qiang Xue committed
242
	abstract protected function getValue($key);
Qiang Xue committed
243 244 245 246

	/**
	 * Stores a value identified by a key in cache.
	 * This method should be implemented by child classes to store the data
Qiang Xue committed
247
	 * in specific cache storage.
Qiang Xue committed
248 249 250 251 252
	 * @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
253
	abstract protected function setValue($key, $value, $expire);
Qiang Xue committed
254 255 256 257

	/**
	 * Stores a value identified by a key into cache if the cache does not contain this key.
	 * This method should be implemented by child classes to store the data
Qiang Xue committed
258
	 * in specific cache storage.
Qiang Xue committed
259 260 261 262 263
	 * @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
264
	abstract protected function addValue($key, $value, $expire);
Qiang Xue committed
265 266 267 268 269 270 271

	/**
	 * Deletes a value with the specified key from cache
	 * This method should be implemented by child classes to delete the data from actual cache storage.
	 * @param string $key the key of the value to be deleted
	 * @return boolean if no error happens during deletion
	 */
Qiang Xue committed
272
	abstract protected function deleteValue($key);
Qiang Xue committed
273 274 275 276 277 278

	/**
	 * Deletes all values from cache.
	 * Child classes may implement this method to realize the flush operation.
	 * @return boolean whether the flush operation was successful.
	 */
Qiang Xue committed
279 280 281 282 283 284 285 286 287 288 289
	abstract protected function flushValues();

	/**
	 * Retrieves multiple values from cache with the specified keys.
	 * The default implementation calls [[getValue()]] multiple times to retrieve
	 * the cached values one by one. If the underlying cache storage supports multiget,
	 * this method should be overridden to exploit that feature.
	 * @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
290
	{
Qiang Xue committed
291 292 293 294 295
		$results = array();
		foreach ($keys as $key) {
			$results[$key] = $this->getValue($key);
		}
		return $results;
Qiang Xue committed
296 297 298 299 300
	}

	/**
	 * Returns whether there is a cache entry with a specified key.
	 * This method is required by the interface ArrayAccess.
301
	 * @param string $key a key identifying the cached value
Qiang Xue committed
302 303
	 * @return boolean
	 */
304
	public function offsetExists($key)
Qiang Xue committed
305
	{
306
		return $this->get($key) !== false;
Qiang Xue committed
307 308 309 310 311
	}

	/**
	 * Retrieves the value from cache with a specified key.
	 * This method is required by the interface ArrayAccess.
312
	 * @param string $key a key identifying the cached value
Qiang Xue committed
313 314
	 * @return mixed the value stored in cache, false if the value is not in the cache or expired.
	 */
315
	public function offsetGet($key)
Qiang Xue committed
316
	{
317
		return $this->get($key);
Qiang Xue committed
318 319 320 321 322
	}

	/**
	 * Stores the value identified by a key into cache.
	 * If the cache already contains such a key, the existing value will be
Qiang Xue committed
323
	 * replaced with the new ones. To add expiration and dependencies, use the [[set()]] method.
Qiang Xue committed
324
	 * This method is required by the interface ArrayAccess.
325
	 * @param string $key the key identifying the value to be cached
Qiang Xue committed
326 327
	 * @param mixed $value the value to be cached
	 */
328
	public function offsetSet($key, $value)
Qiang Xue committed
329
	{
330
		$this->set($key, $value);
Qiang Xue committed
331 332 333 334 335
	}

	/**
	 * Deletes the value with the specified key from cache
	 * This method is required by the interface ArrayAccess.
336
	 * @param string $key the key of the value to be deleted
Qiang Xue committed
337
	 */
338
	public function offsetUnset($key)
Qiang Xue committed
339
	{
340
		$this->delete($key);
Qiang Xue committed
341 342
	}
}