PageCache.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312
  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\filters;
  8. use Yii;
  9. use yii\base\Action;
  10. use yii\base\ActionFilter;
  11. use yii\base\DynamicContentAwareInterface;
  12. use yii\base\DynamicContentAwareTrait;
  13. use yii\caching\CacheInterface;
  14. use yii\caching\Dependency;
  15. use yii\di\Instance;
  16. use yii\web\Response;
  17. /**
  18. * PageCache implements server-side caching of whole pages.
  19. *
  20. * It is an action filter that can be added to a controller and handles the `beforeAction` event.
  21. *
  22. * To use PageCache, declare it in the `behaviors()` method of your controller class.
  23. * In the following example the filter will be applied to the `index` action and
  24. * cache the whole page for maximum 60 seconds or until the count of entries in the post table changes.
  25. * It also stores different versions of the page depending on the application language.
  26. *
  27. * ```php
  28. * public function behaviors()
  29. * {
  30. * return [
  31. * 'pageCache' => [
  32. * 'class' => 'yii\filters\PageCache',
  33. * 'only' => ['index'],
  34. * 'duration' => 60,
  35. * 'dependency' => [
  36. * 'class' => 'yii\caching\DbDependency',
  37. * 'sql' => 'SELECT COUNT(*) FROM post',
  38. * ],
  39. * 'variations' => [
  40. * \Yii::$app->language,
  41. * ]
  42. * ],
  43. * ];
  44. * }
  45. * ```
  46. *
  47. * @author Qiang Xue <qiang.xue@gmail.com>
  48. * @author Sergey Makinen <sergey@makinen.ru>
  49. * @since 2.0
  50. */
  51. class PageCache extends ActionFilter implements DynamicContentAwareInterface
  52. {
  53. use DynamicContentAwareTrait;
  54. /**
  55. * Page cache version, to detect incompatibilities in cached values when the
  56. * data format of the cache changes.
  57. */
  58. const PAGE_CACHE_VERSION = 1;
  59. /**
  60. * @var bool whether the content being cached should be differentiated according to the route.
  61. * A route consists of the requested controller ID and action ID. Defaults to `true`.
  62. */
  63. public $varyByRoute = true;
  64. /**
  65. * @var CacheInterface|array|string the cache object or the application component ID of the cache object.
  66. * After the PageCache object is created, if you want to change this property,
  67. * you should only assign it with a cache object.
  68. * Starting from version 2.0.2, this can also be a configuration array for creating the object.
  69. */
  70. public $cache = 'cache';
  71. /**
  72. * @var int number of seconds that the data can remain valid in cache.
  73. * Use `0` to indicate that the cached data will never expire.
  74. */
  75. public $duration = 60;
  76. /**
  77. * @var array|Dependency the dependency that the cached content depends on.
  78. * This can be either a [[Dependency]] object or a configuration array for creating the dependency object.
  79. * For example,
  80. *
  81. * ```php
  82. * [
  83. * 'class' => 'yii\caching\DbDependency',
  84. * 'sql' => 'SELECT MAX(updated_at) FROM post',
  85. * ]
  86. * ```
  87. *
  88. * would make the output cache depend on the last modified time of all posts.
  89. * If any post has its modification time changed, the cached content would be invalidated.
  90. *
  91. * If [[cacheCookies]] or [[cacheHeaders]] is enabled, then [[\yii\caching\Dependency::reusable]] should be enabled as well to save performance.
  92. * This is because the cookies and headers are currently stored separately from the actual page content, causing the dependency to be evaluated twice.
  93. */
  94. public $dependency;
  95. /**
  96. * @var string[]|string list of factors that would cause the variation of the content being cached.
  97. * Each factor is a string representing a variation (e.g. the language, a GET parameter).
  98. * The following variation setting will cause the content to be cached in different versions
  99. * according to the current application language:
  100. *
  101. * ```php
  102. * [
  103. * Yii::$app->language,
  104. * ]
  105. * ```
  106. */
  107. public $variations;
  108. /**
  109. * @var bool whether to enable the page cache. You may use this property to turn on and off
  110. * the page cache according to specific setting (e.g. enable page cache only for GET requests).
  111. */
  112. public $enabled = true;
  113. /**
  114. * @var \yii\base\View the view component to use for caching. If not set, the default application view component
  115. * [[\yii\web\Application::view]] will be used.
  116. */
  117. public $view;
  118. /**
  119. * @var bool|array a boolean value indicating whether to cache all cookies, or an array of
  120. * cookie names indicating which cookies can be cached. Be very careful with caching cookies, because
  121. * it may leak sensitive or private data stored in cookies to unwanted users.
  122. * @since 2.0.4
  123. */
  124. public $cacheCookies = false;
  125. /**
  126. * @var bool|array a boolean value indicating whether to cache all HTTP headers, or an array of
  127. * HTTP header names (case-insensitive) indicating which HTTP headers can be cached.
  128. * Note if your HTTP headers contain sensitive information, you should white-list which headers can be cached.
  129. * @since 2.0.4
  130. */
  131. public $cacheHeaders = true;
  132. /**
  133. * {@inheritdoc}
  134. */
  135. public function init()
  136. {
  137. parent::init();
  138. if ($this->view === null) {
  139. $this->view = Yii::$app->getView();
  140. }
  141. }
  142. /**
  143. * This method is invoked right before an action is to be executed (after all possible filters.)
  144. * You may override this method to do last-minute preparation for the action.
  145. * @param Action $action the action to be executed.
  146. * @return bool whether the action should continue to be executed.
  147. */
  148. public function beforeAction($action)
  149. {
  150. if (!$this->enabled) {
  151. return true;
  152. }
  153. $this->cache = Instance::ensure($this->cache, 'yii\caching\CacheInterface');
  154. if (is_array($this->dependency)) {
  155. $this->dependency = Yii::createObject($this->dependency);
  156. }
  157. $response = Yii::$app->getResponse();
  158. $data = $this->cache->get($this->calculateCacheKey());
  159. if (!is_array($data) || !isset($data['cacheVersion']) || $data['cacheVersion'] !== static::PAGE_CACHE_VERSION) {
  160. $this->view->pushDynamicContent($this);
  161. ob_start();
  162. ob_implicit_flush(false);
  163. $response->on(Response::EVENT_AFTER_SEND, [$this, 'cacheResponse']);
  164. Yii::debug('Valid page content is not found in the cache.', __METHOD__);
  165. return true;
  166. }
  167. $this->restoreResponse($response, $data);
  168. Yii::debug('Valid page content is found in the cache.', __METHOD__);
  169. return false;
  170. }
  171. /**
  172. * This method is invoked right before the response caching is to be started.
  173. * You may override this method to cancel caching by returning `false` or store an additional data
  174. * in a cache entry by returning an array instead of `true`.
  175. * @return bool|array whether to cache or not, return an array instead of `true` to store an additional data.
  176. * @since 2.0.11
  177. */
  178. public function beforeCacheResponse()
  179. {
  180. return true;
  181. }
  182. /**
  183. * This method is invoked right after the response restoring is finished (but before the response is sent).
  184. * You may override this method to do last-minute preparation before the response is sent.
  185. * @param array|null $data an array of an additional data stored in a cache entry or `null`.
  186. * @since 2.0.11
  187. */
  188. public function afterRestoreResponse($data)
  189. {
  190. }
  191. /**
  192. * Restores response properties from the given data.
  193. * @param Response $response the response to be restored.
  194. * @param array $data the response property data.
  195. * @since 2.0.3
  196. */
  197. protected function restoreResponse($response, $data)
  198. {
  199. foreach (['format', 'version', 'statusCode', 'statusText', 'content'] as $name) {
  200. $response->{$name} = $data[$name];
  201. }
  202. foreach (['headers', 'cookies'] as $name) {
  203. if (isset($data[$name]) && is_array($data[$name])) {
  204. $response->{$name}->fromArray(array_merge($data[$name], $response->{$name}->toArray()));
  205. }
  206. }
  207. if (!empty($data['dynamicPlaceholders']) && is_array($data['dynamicPlaceholders'])) {
  208. $response->content = $this->updateDynamicContent($response->content, $data['dynamicPlaceholders'], true);
  209. }
  210. $this->afterRestoreResponse(isset($data['cacheData']) ? $data['cacheData'] : null);
  211. }
  212. /**
  213. * Caches response properties.
  214. * @since 2.0.3
  215. */
  216. public function cacheResponse()
  217. {
  218. $this->view->popDynamicContent();
  219. $beforeCacheResponseResult = $this->beforeCacheResponse();
  220. if ($beforeCacheResponseResult === false) {
  221. echo $this->updateDynamicContent(ob_get_clean(), $this->getDynamicPlaceholders());
  222. return;
  223. }
  224. $response = Yii::$app->getResponse();
  225. $data = [
  226. 'cacheVersion' => static::PAGE_CACHE_VERSION,
  227. 'cacheData' => is_array($beforeCacheResponseResult) ? $beforeCacheResponseResult : null,
  228. 'content' => ob_get_clean(),
  229. ];
  230. if ($data['content'] === false || $data['content'] === '') {
  231. return;
  232. }
  233. $data['dynamicPlaceholders'] = $this->getDynamicPlaceholders();
  234. foreach (['format', 'version', 'statusCode', 'statusText'] as $name) {
  235. $data[$name] = $response->{$name};
  236. }
  237. $this->insertResponseCollectionIntoData($response, 'headers', $data);
  238. $this->insertResponseCollectionIntoData($response, 'cookies', $data);
  239. $this->cache->set($this->calculateCacheKey(), $data, $this->duration, $this->dependency);
  240. $data['content'] = $this->updateDynamicContent($data['content'], $this->getDynamicPlaceholders());
  241. echo $data['content'];
  242. }
  243. /**
  244. * Inserts (or filters/ignores according to config) response headers/cookies into a cache data array.
  245. * @param Response $response the response.
  246. * @param string $collectionName currently it's `headers` or `cookies`.
  247. * @param array $data the cache data.
  248. */
  249. private function insertResponseCollectionIntoData(Response $response, $collectionName, array &$data)
  250. {
  251. $property = 'cache' . ucfirst($collectionName);
  252. if ($this->{$property} === false) {
  253. return;
  254. }
  255. $all = $response->{$collectionName}->toArray();
  256. if (is_array($this->{$property})) {
  257. $filtered = [];
  258. foreach ($this->{$property} as $name) {
  259. if ($collectionName === 'headers') {
  260. $name = strtolower($name);
  261. }
  262. if (isset($all[$name])) {
  263. $filtered[$name] = $all[$name];
  264. }
  265. }
  266. $all = $filtered;
  267. }
  268. $data[$collectionName] = $all;
  269. }
  270. /**
  271. * @return array the key used to cache response properties.
  272. * @since 2.0.3
  273. */
  274. protected function calculateCacheKey()
  275. {
  276. $key = [__CLASS__];
  277. if ($this->varyByRoute) {
  278. $key[] = Yii::$app->requestedRoute;
  279. }
  280. return array_merge($key, (array)$this->variations);
  281. }
  282. /**
  283. * {@inheritdoc}
  284. */
  285. public function getView()
  286. {
  287. return $this->view;
  288. }
  289. }