Cache.php 12.2 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 12 13
namespace yii\caching;

use yii\base\ApplicationComponent;

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
 *
Qiang Xue committed
23
 * Derived classes should implement the following methods:
Qiang Xue committed
24
 *
Qiang Xue committed
25 26 27 28 29
 * - [[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
30
 *
Qiang Xue committed
31
 * Because Cache implements the ArrayAccess interface, it can be used like an array. For example,
Qiang Xue committed
32
 *
Qiang Xue committed
33 34 35 36
 * ~~~
 * $cache['foo'] = 'some data';
 * echo $cache['foo'];
 * ~~~
Qiang Xue committed
37 38
 *
 * @author Qiang Xue <qiang.xue@gmail.com>
Qiang Xue committed
39
 * @since 2.0
Qiang Xue committed
40
 */
Qiang Xue committed
41
abstract class Cache extends ApplicationComponent implements \ArrayAccess
Qiang Xue committed
42 43
{
	/**
Qiang Xue committed
44 45 46 47
	 * @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
48 49 50
	 */
	public $keyPrefix;
	/**
Qiang Xue committed
51 52 53
	 * @var boolean whether to hash the cache keys so that they can fit in the underlying cache storage.
	 * Defaults to true. If you set this to be false, you have to make sure the cache keys are allowed by
	 * the cache storage.
Qiang Xue committed
54
	 **/
Qiang Xue committed
55
	public $hashKey = true;
Qiang Xue committed
56
	/**
Qiang Xue committed
57 58 59 60 61 62
	 * @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
63
	 * you are using [[Dependency|cache dependency]], because it relies on data serialization.
Qiang Xue committed
64
	 */
Qiang Xue committed
65
	public $serializer;
Qiang Xue committed
66

Qiang Xue committed
67 68 69 70 71 72 73
	/**
	 * Initializes the application component.
	 * This method overrides the parent implementation by setting default cache key prefix.
	 */
	public function init()
	{
		parent::init();
Qiang Xue committed
74
		if ($this->keyPrefix === null) {
Qiang Xue committed
75
			$this->keyPrefix = \Yii::$application->id;
Qiang Xue committed
76
		}
Qiang Xue committed
77 78 79
	}

	/**
Qiang Xue committed
80
	 * Generates a cache key from a given key.
Qiang Xue committed
81
	 * @param string $key a key identifying a value to be cached
Qiang Xue committed
82
	 * @return string a key generated from the provided key which ensures the uniqueness across applications
Qiang Xue committed
83
	 */
Qiang Xue committed
84
	protected function generateCacheKey($key)
Qiang Xue committed
85
	{
Qiang Xue committed
86
		return $this->hashKey ? md5($this->keyPrefix . $key) : $this->keyPrefix . $key;
Qiang Xue committed
87 88 89 90 91
	}

	/**
	 * Retrieves a value from cache with a specified key.
	 * @param string $id a key identifying the cached value
Qiang Xue committed
92 93
	 * @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
94 95 96
	 */
	public function get($id)
	{
Qiang Xue committed
97 98 99 100 101 102 103 104
		$value = $this->getValue($this->generateCacheKey($id));
		if ($value === false || $this->serializer === false) {
			return $value;
		} elseif ($this->serializer === null) {
			$value = unserialize($value);
		} else {
			$value = call_user_func($this->serializer[1], $value);
		}
Qiang Xue committed
105
		if (is_array($value) && ($value[1] instanceof Dependency) || !$value[1]->getHasChanged()) {
Qiang Xue committed
106 107 108
			return $value[0];
		} else {
			return false;
Qiang Xue committed
109 110 111 112 113
		}
	}

	/**
	 * Retrieves multiple values from cache with the specified keys.
Qiang Xue committed
114 115 116
	 * 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.
Qiang Xue committed
117 118 119 120 121
	 * @param array $ids list of keys identifying the cached values
	 * @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.
	 */
Qiang Xue committed
122
	public function mget(array $ids)
Qiang Xue committed
123
	{
Qiang Xue committed
124
		$uids = array();
Qiang Xue committed
125
		foreach ($ids as $id) {
Qiang Xue committed
126
			$uids[$id] = $this->generateCacheKey($id);
Qiang Xue committed
127
		}
Qiang Xue committed
128 129 130 131 132
		$values = $this->getValues($uids);
		$results = array();
		if ($this->serializer === false) {
			foreach ($uids as $id => $uid) {
				$results[$id] = isset($values[$uid]) ? $values[$uid] : false;
Qiang Xue committed
133
			}
Qiang Xue committed
134 135 136 137 138
		} else {
			foreach ($uids as $id => $uid) {
				$results[$id] = false;
				if (isset($values[$uid])) {
					$value = $this->serializer === null ? unserialize($values[$uid]) : call_user_func($this->serializer[1], $values[$uid]);
Qiang Xue committed
139
					if (is_array($value) && (!($value[1] instanceof Dependency) || !$value[1]->getHasChanged())) {
Qiang Xue committed
140 141 142
						$results[$id] = $value[0];
					}
				}
Qiang Xue committed
143 144 145 146 147 148 149 150
			}
		}
		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
151
	 * expiration time will be replaced with the new ones, respectively.
Qiang Xue committed
152 153 154 155
	 *
	 * @param string $id the key identifying the value to be cached
	 * @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
156
	 * @param Dependency $dependency dependency of the cached item. If the dependency changes,
Qiang Xue committed
157 158
	 * the corresponding value in the cache will be invalidated when it is fetched via [[get()]].
	 * @return boolean whether the value is successfully stored into cache
Qiang Xue committed
159
	 */
Qiang Xue committed
160
	public function set($id, $value, $expire = 0, $dependency = null)
Qiang Xue committed
161
	{
Qiang Xue committed
162
		if ($dependency !== null && $this->serializer !== false) {
Qiang Xue committed
163
			$dependency->evaluateDependency();
Qiang Xue committed
164
		}
Qiang Xue committed
165
		if ($this->serializer === null) {
Qiang Xue committed
166
			$value = serialize(array($value, $dependency));
Qiang Xue committed
167
		} elseif ($this->serializer !== false) {
Qiang Xue committed
168
			$value = call_user_func($this->serializer[0], array($value, $dependency));
Qiang Xue committed
169 170
		}
		return $this->setValue($this->generateCacheKey($id), $value, $expire);
Qiang Xue committed
171 172 173 174 175 176 177 178
	}

	/**
	 * 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.
	 * @param string $id the key identifying the value to be cached
	 * @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
179
	 * @param Dependency $dependency dependency of the cached item. If the dependency changes,
Qiang Xue committed
180 181
	 * the corresponding value in the cache will be invalidated when it is fetched via [[get()]].
	 * @return boolean whether the value is successfully stored into cache
Qiang Xue committed
182
	 */
Qiang Xue committed
183
	public function add($id, $value, $expire = 0, $dependency = null)
Qiang Xue committed
184
	{
Qiang Xue committed
185
		if ($dependency !== null && $this->serializer !== false) {
Qiang Xue committed
186
			$dependency->evaluateDependency();
Qiang Xue committed
187
		}
Qiang Xue committed
188
		if ($this->serializer === null) {
Qiang Xue committed
189
			$value = serialize(array($value, $dependency));
Qiang Xue committed
190
		} elseif ($this->serializer !== false) {
Qiang Xue committed
191
			$value = call_user_func($this->serializer[0], array($value, $dependency));
Qiang Xue committed
192 193
		}
		return $this->addValue($this->generateCacheKey($id), $value, $expire);
Qiang Xue committed
194 195 196 197 198 199 200 201 202
	}

	/**
	 * Deletes a value with the specified key from cache
	 * @param string $id the key of the value to be deleted
	 * @return boolean if no error happens during deletion
	 */
	public function delete($id)
	{
Qiang Xue committed
203
		return $this->deleteValue($this->generateCacheKey($id));
Qiang Xue committed
204 205 206 207
	}

	/**
	 * Deletes all values from cache.
Qiang Xue committed
208
	 * Be careful of performing this operation if the cache is shared among multiple applications.
Qiang Xue committed
209 210 211 212 213 214 215 216 217 218
	 * @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
219
	 * from specific cache storage.
Qiang Xue committed
220 221 222
	 * @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
223
	abstract protected function getValue($key);
Qiang Xue committed
224 225 226 227

	/**
	 * Stores a value identified by a key in cache.
	 * This method should be implemented by child classes to store the data
Qiang Xue committed
228
	 * in specific cache storage.
Qiang Xue committed
229 230 231 232 233
	 * @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
234
	abstract protected function setValue($key, $value, $expire);
Qiang Xue committed
235 236 237 238

	/**
	 * 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
239
	 * in specific cache storage.
Qiang Xue committed
240 241 242 243 244
	 * @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
245
	abstract protected function addValue($key, $value, $expire);
Qiang Xue committed
246 247 248 249 250 251 252

	/**
	 * 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
253
	abstract protected function deleteValue($key);
Qiang Xue committed
254 255 256 257 258 259

	/**
	 * 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
260 261 262 263 264 265 266 267 268 269 270
	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
271
	{
Qiang Xue committed
272 273 274 275 276
		$results = array();
		foreach ($keys as $key) {
			$results[$key] = $this->getValue($key);
		}
		return $results;
Qiang Xue committed
277 278 279 280 281 282 283 284 285 286
	}

	/**
	 * Returns whether there is a cache entry with a specified key.
	 * This method is required by the interface ArrayAccess.
	 * @param string $id a key identifying the cached value
	 * @return boolean
	 */
	public function offsetExists($id)
	{
Qiang Xue committed
287
		return $this->get($id) !== false;
Qiang Xue committed
288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303
	}

	/**
	 * Retrieves the value from cache with a specified key.
	 * This method is required by the interface ArrayAccess.
	 * @param string $id a key identifying the cached value
	 * @return mixed the value stored in cache, false if the value is not in the cache or expired.
	 */
	public function offsetGet($id)
	{
		return $this->get($id);
	}

	/**
	 * 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
304
	 * replaced with the new ones. To add expiration and dependencies, use the [[set()]] method.
Qiang Xue committed
305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323
	 * This method is required by the interface ArrayAccess.
	 * @param string $id the key identifying the value to be cached
	 * @param mixed $value the value to be cached
	 */
	public function offsetSet($id, $value)
	{
		$this->set($id, $value);
	}

	/**
	 * Deletes the value with the specified key from cache
	 * This method is required by the interface ArrayAccess.
	 * @param string $id the key of the value to be deleted
	 */
	public function offsetUnset($id)
	{
		$this->delete($id);
	}
}