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

namespace yii\widgets;

Qiang Xue committed
10 11
use Yii;
use yii\base\InvalidConfigException;
12
use yii\base\Widget;
Qiang Xue committed
13 14
use yii\caching\Cache;
use yii\caching\Dependency;
15 16 17 18 19 20 21 22 23 24 25 26

/**
 * @author Qiang Xue <qiang.xue@gmail.com>
 * @since 2.0
 */
class FragmentCache extends Widget
{
	/**
	 * @var string the ID of the cache application component. Defaults to 'cache' (the primary cache application component.)
	 */
	public $cacheID = 'cache';
	/**
Qiang Xue committed
27 28
	 * @var integer number of seconds that the data can remain valid in cache.
	 * Use 0 to indicate that the cached data will never expire.
29 30 31
	 */
	public $duration = 60;
	/**
Qiang Xue committed
32 33 34 35 36
	 * @var array|Dependency the dependency that the cached content depends on.
	 * This can be either a [[Dependency]] object or a configuration array for creating the dependency object.
	 * For example,
	 *
	 * ~~~
37
	 * array(
Qiang Xue committed
38 39
	 *     'class' => 'yii\caching\DbDependency',
	 *     'sql' => 'SELECT MAX(lastModified) FROM Post',
40
	 * )
Qiang Xue committed
41 42
	 * ~~~
	 *
43 44 45 46 47
	 * would make the output cache depends on the last modified time of all posts.
	 * If any post has its modification time changed, the cached content would be invalidated.
	 */
	public $dependency;
	/**
Qiang Xue committed
48 49 50 51 52 53 54 55 56
	 * @var array list of factors that would cause the variation of the content being cached.
	 * Each factor is a string representing a variation (e.g. the language, a GET parameter).
	 * The following variation setting will cause the content to be cached in different versions
	 * according to the current application language:
	 *
	 * ~~~
	 * array(
	 *     Yii::$app->language,
	 * )
57
	 */
Qiang Xue committed
58
	public $variations;
59
	/**
Qiang Xue committed
60 61
	 * @var boolean whether to enable the fragment cache. You may use this property to turn on and off
	 * the fragment cache according to specific setting (e.g. enable fragment cache only for GET requests).
62
	 */
Qiang Xue committed
63
	public $enabled = true;
64 65 66 67 68 69 70 71 72

	/**
	 * Marks the start of content to be cached.
	 * Content displayed after this method call and before {@link endCache()}
	 * will be captured and saved in cache.
	 * This method does nothing if valid content is already found in cache.
	 */
	public function init()
	{
Qiang Xue committed
73
		if ($this->getCachedContent() === false && $this->getCache() !== null) {
74 75 76 77 78 79 80 81 82 83 84 85 86
			ob_start();
			ob_implicit_flush(false);
		}
	}

	/**
	 * Marks the end of content to be cached.
	 * Content displayed before this method call and after {@link init()}
	 * will be captured and saved in cache.
	 * This method does nothing if valid content is already found in cache.
	 */
	public function run()
	{
Qiang Xue committed
87 88 89 90
		if (($content = $this->getCachedContent()) !== false) {
			echo $content;
		} elseif (($cache = $this->getCache()) !== false) {
			$content = ob_get_clean();
91
			if (is_array($this->dependency)) {
Qiang Xue committed
92
				$this->dependency = Yii::createObject($this->dependency);
93
			}
Qiang Xue committed
94 95
			$cache->set($this->calculateKey(), $content, $this->duration, $this->dependency);
			echo $content;
96 97 98 99
		}
	}

	/**
Qiang Xue committed
100
	 * @var string|boolean the cached content. False if the content is not cached.
101
	 */
Qiang Xue committed
102
	private $_content;
103 104

	/**
Qiang Xue committed
105 106
	 * Returns the cached content if available.
	 * @return string|boolean the cached content. False is returned if valid content is not found in the cache.
107
	 */
Qiang Xue committed
108
	public function getCachedContent()
109
	{
Qiang Xue committed
110 111 112 113 114 115
		if ($this->_content === null) {
			if (($cache = $this->getCache()) !== null) {
				$key = $this->calculateKey();
				$this->_content = $cache->get($key);
			} else {
				$this->_content = false;
116 117
			}
		}
Qiang Xue committed
118
		return $this->_content;
119 120 121
	}

	/**
Qiang Xue committed
122 123 124
	 * Generates a unique key used for storing the content in cache.
	 * The key generated depends on both [[id]] and [[variations]].
	 * @return string a valid cache key
125
	 */
Qiang Xue committed
126
	protected function calculateKey()
127
	{
Qiang Xue committed
128 129 130 131 132 133 134
		$factors = array(__CLASS__, $this->getId());
		if (is_array($this->variations)) {
			foreach ($this->variations as $factor) {
				$factors[] = $factor;
			}
		}
		return $this->getCache()->buildKey($factors);
135 136 137
	}

	/**
Qiang Xue committed
138
	 * @var Cache
139
	 */
Qiang Xue committed
140
	private $_cache;
141 142

	/**
Qiang Xue committed
143 144 145 146
	 * Returns the cache instance used for storing content.
	 * @return Cache the cache instance. Null is returned if the cache component is not available
	 * or [[enabled]] is false.
	 * @throws InvalidConfigException if [[cacheID]] does not point to a valid application component.
147
	 */
Qiang Xue committed
148
	public function getCache()
149
	{
Qiang Xue committed
150 151 152 153 154 155 156 157 158
		if (!$this->enabled) {
			return null;
		}
		if ($this->_cache === null) {
			$cache = Yii::$app->getComponent($this->cacheID);
			if ($cache instanceof Cache) {
				$this->_cache = $cache;
			} else {
				throw new InvalidConfigException('FragmentCache::cacheID must refer to the ID of a cache application component.');
159 160
			}
		}
Qiang Xue committed
161
		return $this->_cache;
162 163 164
	}

	/**
Qiang Xue committed
165 166
	 * Sets the cache instance used by the session component.
	 * @param Cache $value the cache instance
167
	 */
Qiang Xue committed
168
	public function setCache($value)
169
	{
Qiang Xue committed
170
		$this->_cache = $value;
171 172
	}
}