You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

188 lines
6.3KB

  1. <?php
  2. /**
  3. * @link http://www.yiiframework.com/
  4. * @copyright Copyright (c) 2008 Yii Software LLC
  5. * @license http://www.yiiframework.com/license/
  6. */
  7. namespace yii\widgets;
  8. use Yii;
  9. use yii\base\Widget;
  10. use yii\caching\Cache;
  11. use yii\caching\Dependency;
  12. use yii\di\Instance;
  13. /**
  14. *
  15. * @property string|boolean $cachedContent The cached content. False is returned if valid content is not found
  16. * in the cache. This property is read-only.
  17. *
  18. * @author Qiang Xue <qiang.xue@gmail.com>
  19. * @since 2.0
  20. */
  21. class FragmentCache extends Widget
  22. {
  23. /**
  24. * @var Cache|array|string the cache object or the application component ID of the cache object.
  25. * After the FragmentCache object is created, if you want to change this property,
  26. * you should only assign it with a cache object.
  27. * Starting from version 2.0.2, this can also be a configuration array for creating the object.
  28. */
  29. public $cache = 'cache';
  30. /**
  31. * @var integer number of seconds that the data can remain valid in cache.
  32. * Use 0 to indicate that the cached data will never expire.
  33. */
  34. public $duration = 60;
  35. /**
  36. * @var array|Dependency the dependency that the cached content depends on.
  37. * This can be either a [[Dependency]] object or a configuration array for creating the dependency object.
  38. * For example,
  39. *
  40. * ~~~
  41. * [
  42. * 'class' => 'yii\caching\DbDependency',
  43. * 'sql' => 'SELECT MAX(updated_at) FROM post',
  44. * ]
  45. * ~~~
  46. *
  47. * would make the output cache depends on the last modified time of all posts.
  48. * If any post has its modification time changed, the cached content would be invalidated.
  49. */
  50. public $dependency;
  51. /**
  52. * @var array list of factors that would cause the variation of the content being cached.
  53. * Each factor is a string representing a variation (e.g. the language, a GET parameter).
  54. * The following variation setting will cause the content to be cached in different versions
  55. * according to the current application language:
  56. *
  57. * ~~~
  58. * [
  59. * Yii::$app->language,
  60. * ]
  61. */
  62. public $variations;
  63. /**
  64. * @var boolean whether to enable the fragment cache. You may use this property to turn on and off
  65. * the fragment cache according to specific setting (e.g. enable fragment cache only for GET requests).
  66. */
  67. public $enabled = true;
  68. /**
  69. * @var array a list of placeholders for embedding dynamic contents. This property
  70. * is used internally to implement the content caching feature. Do not modify it.
  71. */
  72. public $dynamicPlaceholders;
  73. /**
  74. * Initializes the FragmentCache object.
  75. */
  76. public function init()
  77. {
  78. parent::init();
  79. $this->cache = $this->enabled ? Instance::ensure($this->cache, Cache::className()) : null;
  80. if ($this->getCachedContent() === false) {
  81. $this->getView()->cacheStack[] = $this;
  82. ob_start();
  83. ob_implicit_flush(false);
  84. }
  85. }
  86. /**
  87. * Marks the end of content to be cached.
  88. * Content displayed before this method call and after [[init()]]
  89. * will be captured and saved in cache.
  90. * This method does nothing if valid content is already found in cache.
  91. */
  92. public function run()
  93. {
  94. if (($content = $this->getCachedContent()) !== false) {
  95. echo $content;
  96. } elseif ($this->cache instanceof Cache) {
  97. $content = ob_get_clean();
  98. array_pop($this->getView()->cacheStack);
  99. if (is_array($this->dependency)) {
  100. $this->dependency = Yii::createObject($this->dependency);
  101. }
  102. $data = [$content, $this->dynamicPlaceholders];
  103. $this->cache->set($this->calculateKey(), $data, $this->duration, $this->dependency);
  104. if (empty($this->getView()->cacheStack) && !empty($this->dynamicPlaceholders)) {
  105. $content = $this->updateDynamicContent($content, $this->dynamicPlaceholders);
  106. }
  107. echo $content;
  108. }
  109. }
  110. /**
  111. * @var string|boolean the cached content. False if the content is not cached.
  112. */
  113. private $_content;
  114. /**
  115. * Returns the cached content if available.
  116. * @return string|boolean the cached content. False is returned if valid content is not found in the cache.
  117. */
  118. public function getCachedContent()
  119. {
  120. if ($this->_content === null) {
  121. $this->_content = false;
  122. if ($this->cache instanceof Cache) {
  123. $key = $this->calculateKey();
  124. $data = $this->cache->get($key);
  125. if (is_array($data) && count($data) === 2) {
  126. list ($content, $placeholders) = $data;
  127. if (is_array($placeholders) && count($placeholders) > 0) {
  128. if (empty($this->getView()->cacheStack)) {
  129. // outermost cache: replace placeholder with dynamic content
  130. $content = $this->updateDynamicContent($content, $placeholders);
  131. }
  132. foreach ($placeholders as $name => $statements) {
  133. $this->getView()->addDynamicPlaceholder($name, $statements);
  134. }
  135. }
  136. $this->_content = $content;
  137. }
  138. }
  139. }
  140. return $this->_content;
  141. }
  142. /**
  143. * Replaces placeholders in content by results of evaluated dynamic statements.
  144. *
  145. * @param string $content
  146. * @param array $placeholders
  147. * @return string final content
  148. */
  149. protected function updateDynamicContent($content, $placeholders)
  150. {
  151. foreach ($placeholders as $name => $statements) {
  152. $placeholders[$name] = $this->getView()->evaluateDynamicContent($statements);
  153. }
  154. return strtr($content, $placeholders);
  155. }
  156. /**
  157. * Generates a unique key used for storing the content in cache.
  158. * The key generated depends on both [[id]] and [[variations]].
  159. * @return mixed a valid cache key
  160. */
  161. protected function calculateKey()
  162. {
  163. $factors = [__CLASS__, $this->getId()];
  164. if (is_array($this->variations)) {
  165. foreach ($this->variations as $factor) {
  166. $factors[] = $factor;
  167. }
  168. }
  169. return $factors;
  170. }
  171. }