GroupDependency.php 2.15 KB
Newer Older
Qiang Xue committed
1 2 3 4 5 6 7 8
<?php
/**
 * @link http://www.yiiframework.com/
 * @copyright Copyright (c) 2008 Yii Software LLC
 * @license http://www.yiiframework.com/license/
 */

namespace yii\caching;
9

10
use yii\base\InvalidConfigException;
Qiang Xue committed
11 12 13 14 15 16 17 18 19 20 21 22 23

/**
 * GroupDependency marks a cached data item with a group name.
 *
 * You may invalidate the cached data items with the same group name all at once
 * by calling [[invalidate()]].
 *
 * @author Qiang Xue <qiang.xue@gmail.com>
 * @since 2.0
 */
class GroupDependency extends Dependency
{
	/**
24
	 * @var string the group name. This property must be set.
Qiang Xue committed
25 26 27 28 29 30 31 32
	 */
	public $group;

	/**
	 * Generates the data needed to determine if dependency has been changed.
	 * This method does nothing in this class.
	 * @param Cache $cache the cache component that is currently evaluating this dependency
	 * @return mixed the data needed to determine if dependency has been changed.
33
	 * @throws InvalidConfigException if [[group]] is not set.
Qiang Xue committed
34 35 36
	 */
	protected function generateDependencyData($cache)
	{
37 38 39
		if ($this->group === null) {
			throw new InvalidConfigException('GroupDependency::group must be set');
		}
Alexander Makarov committed
40
		$version = $cache->get([__CLASS__, $this->group]);
41
		if ($version === false) {
42
			$version = $this->invalidate($cache, $this->group);
Qiang Xue committed
43
		}
44
		return $version;
Qiang Xue committed
45 46 47 48 49 50
	}

	/**
	 * Performs the actual dependency checking.
	 * @param Cache $cache the cache component that is currently evaluating this dependency
	 * @return boolean whether the dependency is changed or not.
51
	 * @throws InvalidConfigException if [[group]] is not set.
Qiang Xue committed
52 53 54
	 */
	public function getHasChanged($cache)
	{
55 56 57
		if ($this->group === null) {
			throw new InvalidConfigException('GroupDependency::group must be set');
		}
Alexander Makarov committed
58
		$version = $cache->get([__CLASS__, $this->group]);
59
		return $version === false || $version !== $this->data;
Qiang Xue committed
60 61 62 63 64 65
	}

	/**
	 * Invalidates all of the cached data items that have the same [[group]].
	 * @param Cache $cache the cache component that caches the data items
	 * @param string $group the group name
66
	 * @return string the current version number
Qiang Xue committed
67 68 69
	 */
	public static function invalidate($cache, $group)
	{
70
		$version = microtime();
Alexander Makarov committed
71
		$cache->set([__CLASS__, $group], $version);
72
		return $version;
Qiang Xue committed
73 74
	}
}