Skip to content
PHP Ecosystem
Explore

PageCache

API reference › yii › filters › PageCache

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,
]
],
];
}
PropertyTypeDescriptionDefined by
$cacheyii\caching\CacheInterface|array|stringThe cache object or the application component ID of the cache object. Default: 'cache'.PageCache
$cacheCookiesbool|arrayA 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
$cacheHeadersbool|arrayA 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
$dependencyarray|yii\caching\DependencyThe dependency that the cached content depends on. Default: null.PageCache
$durationintNumber of seconds that the data can remain valid in cache. Default: 60.PageCache
$dynamicPlaceholdersarrayA list of placeholders.yii\base\DynamicContentAwareTrait
$enabledboolWhether to enable the page cache. Default: true.PageCache
$exceptarrayList of action IDs that this filter should not apply to. Default: [].yii\base\ActionFilter
$onlyarrayList of action IDs that this filter should apply to. Default: [].yii\base\ActionFilter
$owneryii\base\T|nullThe owner of this behavior Default: null.yii\base\Behavior
$variationsstring[]|string|callableList of factors that would cause the variation of the content being cached. Default: null.PageCache
$varyByRouteboolWhether the content being cached should be differentiated according to the route. Default: true.PageCache
$viewyii\base\View|nullThe view component to use for caching. Default: null.PageCache
MethodDescriptionDefined by
__construct()Constructor.yii\base\BaseObject
__call()Calls the named method which is not a class method.yii\base\BaseObject
__get()Returns the value of an object property.yii\base\BaseObject
__isset()Checks if a property is set, i.e. defined and not null.yii\base\BaseObject
__set()Sets value of an object property.yii\base\BaseObject
__unset()Sets an object property to null.yii\base\BaseObject
addDynamicPlaceholder()Adds a placeholder for dynamic content.yii\base\DynamicContentAwareTrait
afterAction()This method is invoked right after an action is executed.yii\base\ActionFilter
afterFilter()yii\base\ActionFilter
afterRestoreResponse()This method is invoked right after the response restoring is finished (but before the response is sent).PageCache
attach()Attaches the behavior object to the component.yii\base\ActionFilter
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()This method is invoked right before the response caching is to be started.PageCache
beforeFilter()yii\base\ActionFilter
cacheResponse()Caches response properties.PageCache
canGetProperty()Returns a value indicating whether a property can be read.yii\base\BaseObject
canSetProperty()Returns a value indicating whether a property can be set.yii\base\BaseObject
className() staticReturns the fully qualified name of this class.yii\base\BaseObject
detach()Detaches the behavior object from the component.yii\base\ActionFilter
events()Declares event handlers for the $owner’s events.yii\base\Behavior
getDynamicPlaceholders()Returns a list of placeholders for dynamic content. This method is used internally to implement the content caching feature.yii\base\DynamicContentAwareTrait
getView()PageCache
hasMethod()Returns a value indicating whether a method is defined.yii\base\BaseObject
hasProperty()Returns a value indicating whether a property is defined.yii\base\BaseObject
init()Initializes the object.PageCache
setDynamicPlaceholders()Sets a list of placeholders for dynamic content. This method is used internally to implement the content caching feature.yii\base\DynamicContentAwareTrait
calculateCacheKey() protectedPageCache
getActionId() protectedReturns an action ID by converting Action::$uniqueId into an ID relative to the module.yii\base\ActionFilter
isActive() protectedReturns a value indicating whether the filter is active for the given action.yii\base\ActionFilter
restoreResponse() protectedRestores response properties from the given data.PageCache
updateDynamicContent() protectedReplaces placeholders in $content with results of evaluated dynamic statements.yii\base\DynamicContentAwareTrait
ConstantValueDescriptionDefined by
PAGE_CACHE_VERSION1Page cache version, to detect incompatibilities in cached values when the data format of the cache changes.PageCache
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.

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

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

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

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,

[
'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 or $cacheHeaders is enabled, then Dependency::$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.

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.

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).

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.

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.

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

The view component to use for caching.

If not set, the default application view component Application::$view will be used.

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

ParameterTypeDescription
$dataarray|nullAn array of an additional data stored in a cache entry or null.

Returns

mixed

Since

2.0.11

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

ParameterTypeDescription
$actionmixedThe action to be executed.

Returns

bool: Whether the action should continue to be executed.

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

public function cacheResponse(): mixed

Caches response properties.

Returns

mixed

Since

2.0.3

public function getView()
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

protected function calculateCacheKey(): array

Returns

array: The key used to cache response properties.

Since

2.0.3

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

Restores response properties from the given data.

Parameters

ParameterTypeDescription
$responseyii\web\ResponseThe response to be restored.
$dataarrayThe response property data.

Returns

mixed

Since

2.0.3