# PageCache

> PageCache implements server-side caching of whole pages.

[API reference](/docs/api/index.md) › [yii](/docs/api/yii/index.md) › [filters](/docs/api/yii/filters/index.md) › PageCache

| class | `yii\filters\PageCache` |
| --- | --- |
| Extends | [`yii\base\ActionFilter`](/docs/api/yii/base/actionfilter/index.md) » [`yii\base\Behavior`](/docs/api/yii/base/behavior/index.md) » [`yii\base\BaseObject`](/docs/api/yii/base/baseobject/index.md) |
| Implements | [`yii\base\DynamicContentAwareInterface`](/docs/api/yii/base/dynamiccontentawareinterface/index.md), [`yii\base\Configurable`](/docs/api/yii/base/configurable/index.md) |
| Uses traits | [`yii\base\DynamicContentAwareTrait`](/docs/api/yii/base/dynamiccontentawaretrait/index.md) |
| Since | 2.0 |
| Source | [`framework/filters/PageCache.php`](https://github.com/yiisoft/yii2/blob/22.0/framework/filters/PageCache.php#L59) |

PageCache implements server-side caching of whole pages.

It is an action filter that can be added to a controller and handles the `beforeAction` event.

To use PageCache, declare it in the `behaviors()` method of your controller class.
In the following example the filter will be applied to the `index` action and
cache the whole page for maximum 60 seconds or until the count of entries in the post table changes.
It also stores different versions of the page depending on the application language.

```
public function behaviors()
{
    return [
        'pageCache' => [
            'class' => 'yii\filters\PageCache',
            'only' => ['index'],
            'duration' => 60,
            'dependency' => [
                'class' => 'yii\caching\DbDependency',
                'sql' => 'SELECT COUNT(*) FROM post',
            ],
            'variations' => [
                \Yii::$app->language,
            ]
        ],
    ];
}
```

## Properties

| Property | Type | Description | Defined by |
| --- | --- | --- | --- |
| [`$cache`](#property-cache) | [`yii\caching\CacheInterface`](/docs/api/yii/caching/cacheinterface/index.md)`\|array\|string` | The cache object or the application component ID of the cache object. Default: `'cache'`. | `PageCache` |
| [`$cacheCookies`](#property-cacheCookies) | `bool\|array` | A boolean value indicating whether to cache all cookies, or an array of cookie names indicating which cookies can be cached. Default: `false`. Available since 2.0.4. | `PageCache` |
| [`$cacheHeaders`](#property-cacheHeaders) | `bool\|array` | A boolean value indicating whether to cache all HTTP headers, or an array of HTTP header names (case-sensitive) indicating which HTTP headers can be cached. Default: `true`. Available since 2.0.4. | `PageCache` |
| [`$dependency`](#property-dependency) | `array\|`[`yii\caching\Dependency`](/docs/api/yii/caching/dependency/index.md) | The dependency that the cached content depends on. Default: `null`. | `PageCache` |
| [`$duration`](#property-duration) | `int` | Number of seconds that the data can remain valid in cache. Default: `60`. | `PageCache` |
| <span id="property-dynamicPlaceholders"></span>`$dynamicPlaceholders` | `array` | A list of placeholders. | [`yii\base\DynamicContentAwareTrait`](/docs/api/yii/base/dynamiccontentawaretrait/index.md) |
| [`$enabled`](#property-enabled) | `bool` | Whether to enable the page cache. Default: `true`. | `PageCache` |
| <span id="property-except"></span>[`$except`](/docs/api/yii/base/actionfilter/index.md#property-except) | `array` | List of action IDs that this filter should not apply to. Default: `[]`. | [`yii\base\ActionFilter`](/docs/api/yii/base/actionfilter/index.md) |
| <span id="property-only"></span>[`$only`](/docs/api/yii/base/actionfilter/index.md#property-only) | `array` | List of action IDs that this filter should apply to. Default: `[]`. | [`yii\base\ActionFilter`](/docs/api/yii/base/actionfilter/index.md) |
| <span id="property-owner"></span>[`$owner`](/docs/api/yii/base/behavior/index.md#property-owner) | `yii\base\T\|null` | The owner of this behavior Default: `null`. | [`yii\base\Behavior`](/docs/api/yii/base/behavior/index.md) |
| [`$variations`](#property-variations) | `string[]\|string\|callable` | List of factors that would cause the variation of the content being cached. Default: `null`. | `PageCache` |
| [`$varyByRoute`](#property-varyByRoute) | `bool` | Whether the content being cached should be differentiated according to the route. Default: `true`. | `PageCache` |
| [`$view`](#property-view) | [`yii\base\View`](/docs/api/yii/base/view/index.md)`\|null` | The view component to use for caching. Default: `null`. | `PageCache` |

## Methods

| Method | Description | Defined by |
| --- | --- | --- |
| <span id="method-__construct"></span>[`__construct()`](/docs/api/yii/base/baseobject/index.md#method-__construct) | Constructor. | [`yii\base\BaseObject`](/docs/api/yii/base/baseobject/index.md) |
| <span id="method-__call"></span>[`__call()`](/docs/api/yii/base/baseobject/index.md#method-__call) | Calls the named method which is not a class method. | [`yii\base\BaseObject`](/docs/api/yii/base/baseobject/index.md) |
| <span id="method-__get"></span>[`__get()`](/docs/api/yii/base/baseobject/index.md#method-__get) | Returns the value of an object property. | [`yii\base\BaseObject`](/docs/api/yii/base/baseobject/index.md) |
| <span id="method-__isset"></span>[`__isset()`](/docs/api/yii/base/baseobject/index.md#method-__isset) | Checks if a property is set, i.e. defined and not null. | [`yii\base\BaseObject`](/docs/api/yii/base/baseobject/index.md) |
| <span id="method-__set"></span>[`__set()`](/docs/api/yii/base/baseobject/index.md#method-__set) | Sets value of an object property. | [`yii\base\BaseObject`](/docs/api/yii/base/baseobject/index.md) |
| <span id="method-__unset"></span>[`__unset()`](/docs/api/yii/base/baseobject/index.md#method-__unset) | Sets an object property to null. | [`yii\base\BaseObject`](/docs/api/yii/base/baseobject/index.md) |
| <span id="method-addDynamicPlaceholder"></span>[`addDynamicPlaceholder()`](/docs/api/yii/base/dynamiccontentawaretrait/index.md#method-addDynamicPlaceholder) | Adds a placeholder for dynamic content. | [`yii\base\DynamicContentAwareTrait`](/docs/api/yii/base/dynamiccontentawaretrait/index.md) |
| <span id="method-afterAction"></span>[`afterAction()`](/docs/api/yii/base/actionfilter/index.md#method-afterAction) | This method is invoked right after an action is executed. | [`yii\base\ActionFilter`](/docs/api/yii/base/actionfilter/index.md) |
| <span id="method-afterFilter"></span>[`afterFilter()`](/docs/api/yii/base/actionfilter/index.md#method-afterFilter) |  | [`yii\base\ActionFilter`](/docs/api/yii/base/actionfilter/index.md) |
| [`afterRestoreResponse()`](#method-afterRestoreResponse) | This method is invoked right after the response restoring is finished (but before the response is sent). | `PageCache` |
| <span id="method-attach"></span>[`attach()`](/docs/api/yii/base/actionfilter/index.md#method-attach) | Attaches the behavior object to the component. | [`yii\base\ActionFilter`](/docs/api/yii/base/actionfilter/index.md) |
| [`beforeAction()`](#method-beforeAction) | This method is invoked right before an action is to be executed (after all possible filters.) You may override this method to do last-minute preparation for the action. | `PageCache` |
| [`beforeCacheResponse()`](#method-beforeCacheResponse) | This method is invoked right before the response caching is to be started. | `PageCache` |
| <span id="method-beforeFilter"></span>[`beforeFilter()`](/docs/api/yii/base/actionfilter/index.md#method-beforeFilter) |  | [`yii\base\ActionFilter`](/docs/api/yii/base/actionfilter/index.md) |
| [`cacheResponse()`](#method-cacheResponse) | Caches response properties. | `PageCache` |
| <span id="method-canGetProperty"></span>[`canGetProperty()`](/docs/api/yii/base/baseobject/index.md#method-canGetProperty) | Returns a value indicating whether a property can be read. | [`yii\base\BaseObject`](/docs/api/yii/base/baseobject/index.md) |
| <span id="method-canSetProperty"></span>[`canSetProperty()`](/docs/api/yii/base/baseobject/index.md#method-canSetProperty) | Returns a value indicating whether a property can be set. | [`yii\base\BaseObject`](/docs/api/yii/base/baseobject/index.md) |
| <span id="method-className"></span>[`className()`](/docs/api/yii/base/baseobject/index.md#method-className) static | Returns the fully qualified name of this class. | [`yii\base\BaseObject`](/docs/api/yii/base/baseobject/index.md) |
| <span id="method-detach"></span>[`detach()`](/docs/api/yii/base/actionfilter/index.md#method-detach) | Detaches the behavior object from the component. | [`yii\base\ActionFilter`](/docs/api/yii/base/actionfilter/index.md) |
| <span id="method-events"></span>[`events()`](/docs/api/yii/base/behavior/index.md#method-events) | Declares event handlers for the [`$owner`](/docs/api/yii/base/behavior/index.md#property-owner)'s events. | [`yii\base\Behavior`](/docs/api/yii/base/behavior/index.md) |
| <span id="method-getDynamicPlaceholders"></span>[`getDynamicPlaceholders()`](/docs/api/yii/base/dynamiccontentawaretrait/index.md#method-getDynamicPlaceholders) | Returns a list of placeholders for dynamic content. This method is used internally to implement the content caching feature. | [`yii\base\DynamicContentAwareTrait`](/docs/api/yii/base/dynamiccontentawaretrait/index.md) |
| [`getView()`](#method-getView) |  | `PageCache` |
| <span id="method-hasMethod"></span>[`hasMethod()`](/docs/api/yii/base/baseobject/index.md#method-hasMethod) | Returns a value indicating whether a method is defined. | [`yii\base\BaseObject`](/docs/api/yii/base/baseobject/index.md) |
| <span id="method-hasProperty"></span>[`hasProperty()`](/docs/api/yii/base/baseobject/index.md#method-hasProperty) | Returns a value indicating whether a property is defined. | [`yii\base\BaseObject`](/docs/api/yii/base/baseobject/index.md) |
| [`init()`](#method-init) | Initializes the object. | `PageCache` |
| <span id="method-setDynamicPlaceholders"></span>[`setDynamicPlaceholders()`](/docs/api/yii/base/dynamiccontentawaretrait/index.md#method-setDynamicPlaceholders) | Sets a list of placeholders for dynamic content. This method is used internally to implement the content caching feature. | [`yii\base\DynamicContentAwareTrait`](/docs/api/yii/base/dynamiccontentawaretrait/index.md) |
| [`calculateCacheKey()`](#method-calculateCacheKey) protected |  | `PageCache` |
| <span id="method-getActionId"></span>[`getActionId()`](/docs/api/yii/base/actionfilter/index.md#method-getActionId) protected | Returns an action ID by converting [`Action::$uniqueId`](/docs/api/yii/base/action/index.md#property-uniqueId) into an ID relative to the module. | [`yii\base\ActionFilter`](/docs/api/yii/base/actionfilter/index.md) |
| <span id="method-isActive"></span>[`isActive()`](/docs/api/yii/base/actionfilter/index.md#method-isActive) protected | Returns a value indicating whether the filter is active for the given action. | [`yii\base\ActionFilter`](/docs/api/yii/base/actionfilter/index.md) |
| [`restoreResponse()`](#method-restoreResponse) protected | Restores response properties from the given data. | `PageCache` |
| <span id="method-updateDynamicContent"></span>[`updateDynamicContent()`](/docs/api/yii/base/dynamiccontentawaretrait/index.md#method-updateDynamicContent) protected | Replaces placeholders in $content with results of evaluated dynamic statements. | [`yii\base\DynamicContentAwareTrait`](/docs/api/yii/base/dynamiccontentawaretrait/index.md) |

## Constants

| Constant | Value | Description | Defined by |
| --- | --- | --- | --- |
| <span id="const-PAGE_CACHE_VERSION"></span>`PAGE_CACHE_VERSION` | `1` | Page cache version, to detect incompatibilities in cached values when the data format of the cache changes. | `PageCache` |

## Property details

### $cache <span id="property-cache"></span>

```php
public yii\caching\CacheInterface|array|string $cache = 'cache'
```

The cache object or the application component ID of the cache object.

After the PageCache object is created, if you want to change this property,
you should only assign it with a cache object.
Starting from version 2.0.2, this can also be a configuration array for creating the object.

### $cacheCookies <span id="property-cacheCookies"></span>

```php
public bool|array $cacheCookies = false
```

A boolean value indicating whether to cache all cookies, or an array of cookie names indicating which cookies can be cached.

Be very careful with caching cookies, because
it may leak sensitive or private data stored in cookies to unwanted users.

**Since**

2.0.4

### $cacheHeaders <span id="property-cacheHeaders"></span>

```php
public bool|array $cacheHeaders = true
```

A boolean value indicating whether to cache all HTTP headers, or an array of HTTP header names (case-sensitive) indicating which HTTP headers can be cached.

Note if your HTTP headers contain sensitive information, you should white-list which headers can be cached.

**Since**

2.0.4

### $dependency <span id="property-dependency"></span>

```php
public array|yii\caching\Dependency $dependency = null
```

The dependency that the cached content depends on.

This can be either a [`Dependency`](/docs/api/yii/caching/dependency/index.md) object or a configuration array for creating the dependency object.
For example,

```
[
    'class' => 'yii\caching\DbDependency',
    'sql' => 'SELECT MAX(updated_at) FROM post',
]
```

would make the output cache depend on the last modified time of all posts.
If any post has its modification time changed, the cached content would be invalidated.

If [`$cacheCookies`](/docs/api/yii/filters/pagecache/index.md#property-cacheCookies) or [`$cacheHeaders`](/docs/api/yii/filters/pagecache/index.md#property-cacheHeaders) is enabled, then [`Dependency::$reusable`](/docs/api/yii/caching/dependency/index.md#property-reusable) should be enabled as well to save performance.
This is because the cookies and headers are currently stored separately from the actual page content, causing the dependency to be evaluated twice.

### $duration <span id="property-duration"></span>

```php
public int $duration = 60
```

Number of seconds that the data can remain valid in cache.

Use `0` to indicate that the cached data will never expire.

### $enabled <span id="property-enabled"></span>

```php
public bool $enabled = true
```

Whether to enable the page cache.

You may use this property to turn on and off
the page cache according to specific setting (e.g. enable page cache only for GET requests).

### $variations <span id="property-variations"></span>

```php
public string[]|string|callable $variations = null
```

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:

```
[
    Yii::$app->language,
]
```

Since version 2.0.48 you can provide an anonymous function to generate variations. This is especially helpful
when you need to access the User component, which is resolved before the PageCache behavior:

```
'variations' => function() {
    return [
        Yii::$app->language,
        Yii::$app->user->id
    ];
}
```

The callable should return an array.

### $varyByRoute <span id="property-varyByRoute"></span>

```php
public bool $varyByRoute = true
```

Whether the content being cached should be differentiated according to the route.

A route consists of the requested controller ID and action ID. Defaults to `true`.

### $view <span id="property-view"></span>

```php
public yii\base\View|null $view = null
```

The view component to use for caching.

If not set, the default application view component
[`Application::$view`](/docs/api/yii/base/application/index.md#property-view) will be used.

## Method details

### afterRestoreResponse() <span id="method-afterRestoreResponse"></span>

```php
public function afterRestoreResponse(array|null $data): mixed
```

This method is invoked right after the response restoring is finished (but before the response is sent).

You may override this method to do last-minute preparation before the response is sent.

**Parameters**

| Parameter | Type | Description |
| --- | --- | --- |
| `$data` | `array\|null` | An array of an additional data stored in a cache entry or `null`. |

**Returns**

`mixed`

**Since**

2.0.11

### beforeAction() <span id="method-beforeAction"></span>

```php
public function beforeAction(mixed $action): bool
```

This method is invoked right before an action is to be executed (after all possible filters.)
You may override this method to do last-minute preparation for the action.

**Parameters**

| Parameter | Type | Description |
| --- | --- | --- |
| `$action` | `mixed` | The action to be executed. |

**Returns**

`bool`: Whether the action should continue to be executed.

### beforeCacheResponse() <span id="method-beforeCacheResponse"></span>

```php
public function beforeCacheResponse(): bool|array
```

This method is invoked right before the response caching is to be started.

You may override this method to cancel caching by returning `false` or store an additional data
in a cache entry by returning an array instead of `true`.

**Returns**

`bool|array`: Whether to cache or not, return an array instead of `true` to store an additional data.

**Since**

2.0.11

### cacheResponse() <span id="method-cacheResponse"></span>

```php
public function cacheResponse(): mixed
```

Caches response properties.

**Returns**

`mixed`

**Since**

2.0.3

### getView() <span id="method-getView"></span>

```php
public function getView()
```

### init() <span id="method-init"></span>

```php
public function init(): mixed
```

Initializes the object.

This method is invoked at the end of the constructor after the object is initialized with the
given configuration.

**Returns**

`mixed`

### calculateCacheKey() <span id="method-calculateCacheKey"></span>

```php
protected function calculateCacheKey(): array
```

**Returns**

`array`: The key used to cache response properties.

**Since**

2.0.3

### restoreResponse() <span id="method-restoreResponse"></span>

```php
protected function restoreResponse(yii\web\Response $response, array $data): mixed
```

Restores response properties from the given data.

**Parameters**

| Parameter | Type | Description |
| --- | --- | --- |
| `$response` | [`yii\web\Response`](/docs/api/yii/web/response/index.md) | The response to be restored. |
| `$data` | `array` | The response property data. |

**Returns**

`mixed`

**Since**

2.0.3