PageCache
extends ActionFilter
in package
implements
DynamicContentAwareInterface
uses
DynamicContentAwareTrait
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,
]
],
];
}
Tags
Table of Contents
Interfaces
- DynamicContentAwareInterface
- DynamicContentAwareInterface is the interface that should be implemented by classes which support a [[View]] dynamic content feature.
Constants
- PAGE_CACHE_VERSION = 1
- Page cache version, to detect incompatibilities in cached values when the data format of the cache changes.
Properties
- $cache : CacheInterface|array<string|int, mixed>|string
- $cacheCookies : bool|array<string|int, mixed>
- $cacheHeaders : bool|array<string|int, mixed>
- $dependency : array<string|int, mixed>|Dependency
- $duration : int
- $enabled : bool
- $except : array<string|int, mixed>
- $only : array<string|int, mixed>
- $owner : Component|null
- $variations : array<string|int, string>|string|callable
- $varyByRoute : bool
- $view : View|null
- $_attachedEvents : array<string|int, mixed>
- $_dynamicPlaceholders : array<string|int, string>
Methods
- __call() : mixed
- Calls the named method which is not a class method.
- __construct() : mixed
- Constructor.
- __get() : mixed
- Returns the value of an object property.
- __isset() : bool
- Checks if a property is set, i.e. defined and not null.
- __set() : mixed
- Sets value of an object property.
- __unset() : mixed
- Sets an object property to null.
- addDynamicPlaceholder() : mixed
- {@inheritdoc}
- afterAction() : mixed
- This method is invoked right after an action is executed.
- afterFilter() : mixed
- afterRestoreResponse() : mixed
- This method is invoked right after the response restoring is finished (but before the response is sent).
- attach() : mixed
- Attaches the behavior object to the component.
- beforeAction() : 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.
- beforeCacheResponse() : bool|array<string|int, mixed>
- This method is invoked right before the response caching is to be started.
- beforeFilter() : mixed
- cacheResponse() : mixed
- Caches response properties.
- canGetProperty() : bool
- Returns a value indicating whether a property can be read.
- canSetProperty() : bool
- Returns a value indicating whether a property can be set.
- className() : string
- Returns the fully qualified name of this class.
- detach() : mixed
- Detaches the behavior object from the component.
- events() : array<string|int, mixed>
- Declares event handlers for the [[owner]]'s events.
- getDynamicPlaceholders() : mixed
- {@inheritdoc}
- getView() : mixed
- {@inheritdoc}
- hasMethod() : bool
- Returns a value indicating whether a method is defined.
- hasProperty() : bool
- Returns a value indicating whether a property is defined.
- init() : mixed
- Initializes the object.
- setDynamicPlaceholders() : mixed
- {@inheritdoc}
- calculateCacheKey() : array<string|int, mixed>
- getActionId() : string
- Returns an action ID by converting [[Action::$uniqueId]] into an ID relative to the module.
- isActive() : bool
- Returns a value indicating whether the filter is active for the given action.
- restoreResponse() : mixed
- Restores response properties from the given data.
- updateDynamicContent() : string
- Replaces placeholders in $content with results of evaluated dynamic statements.
- insertResponseCookieCollectionIntoData() : mixed
- Inserts (or filters/ignores according to config) response cookies into a cache data array.
- insertResponseHeaderCollectionIntoData() : mixed
- Inserts (or filters/ignores according to config) response headers into a cache data array.
Constants
PAGE_CACHE_VERSION
Page cache version, to detect incompatibilities in cached values when the data format of the cache changes.
public
mixed
PAGE_CACHE_VERSION
= 1
Properties
$cache
public
CacheInterface|array<string|int, mixed>|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
public
bool|array<string|int, mixed>
$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.
Tags
$cacheHeaders
public
bool|array<string|int, mixed>
$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.
Tags
$dependency
public
array<string|int, mixed>|Dependency
$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,
[
'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 [[\yii\caching\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.
$duration
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
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).
$except
public
array<string|int, mixed>
$except
= []
list of action IDs that this filter should not apply to.
Tags
$only
public
array<string|int, mixed>
$only
= []
list of action IDs that this filter should apply to. If this property is not set, then the filter applies to all actions, unless they are listed in [[except]]. If an action ID appears in both [[only]] and [[except]], this filter will NOT apply to it.
Note that if the filter is attached to a module, the action IDs should also include child module IDs (if any) and controller IDs.
Since version 2.0.9 action IDs can be specified as wildcards, e.g. site/*
.
Tags
$owner
public
Component|null
$owner
the owner of this behavior
$variations
public
array<string|int, string>|string|callable
$variations
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
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
public
View|null
$view
the view component to use for caching. If not set, the default application view component [[\yii\web\Application::view]] will be used.
$_attachedEvents
private
array<string|int, mixed>
$_attachedEvents
= []
Attached events handlers
$_dynamicPlaceholders
private
array<string|int, string>
$_dynamicPlaceholders
a list of placeholders for dynamic content
Methods
__call()
Calls the named method which is not a class method.
public
__call(string $name, array<string|int, mixed> $params) : mixed
Do not call this method directly as it is a PHP magic method that will be implicitly called when an unknown method is being invoked.
Parameters
- $name : string
-
the method name
- $params : array<string|int, mixed>
-
method parameters
Tags
Return values
mixed —the method return value
__construct()
Constructor.
public
__construct([array<string|int, mixed> $config = [] ]) : mixed
The default implementation does two things:
- Initializes the object with the given configuration
$config
. - Call [[init()]].
If this method is overridden in a child class, it is recommended that
- the last parameter of the constructor is a configuration array, like
$config
here. - call the parent implementation at the end of the constructor.
Parameters
- $config : array<string|int, mixed> = []
-
name-value pairs that will be used to initialize the object properties
__get()
Returns the value of an object property.
public
__get(string $name) : mixed
Do not call this method directly as it is a PHP magic method that
will be implicitly called when executing $value = $object->property;
.
Parameters
- $name : string
-
the property name
Tags
Return values
mixed —the property value
__isset()
Checks if a property is set, i.e. defined and not null.
public
__isset(string $name) : bool
Do not call this method directly as it is a PHP magic method that
will be implicitly called when executing isset($object->property)
.
Note that if the property is not defined, false will be returned.
Parameters
- $name : string
-
the property name or the event name
Tags
Return values
bool —whether the named property is set (not null).
__set()
Sets value of an object property.
public
__set(string $name, mixed $value) : mixed
Do not call this method directly as it is a PHP magic method that
will be implicitly called when executing $object->property = $value;
.
Parameters
- $name : string
-
the property name or the event name
- $value : mixed
-
the property value
Tags
__unset()
Sets an object property to null.
public
__unset(string $name) : mixed
Do not call this method directly as it is a PHP magic method that
will be implicitly called when executing unset($object->property)
.
Note that if the property is not defined, this method will do nothing. If the property is read-only, it will throw an exception.
Parameters
- $name : string
-
the property name
Tags
addDynamicPlaceholder()
{@inheritdoc}
public
addDynamicPlaceholder(mixed $name, mixed $statements) : mixed
Parameters
- $name : mixed
- $statements : mixed
afterAction()
This method is invoked right after an action is executed.
public
afterAction(Action $action, mixed $result) : mixed
You may override this method to do some postprocessing for the action.
Parameters
- $action : Action
-
the action just executed.
- $result : mixed
-
the action execution result
Return values
mixed —the processed action result.
afterFilter()
public
afterFilter(ActionEvent $event) : mixed
Parameters
- $event : ActionEvent
afterRestoreResponse()
This method is invoked right after the response restoring is finished (but before the response is sent).
public
afterRestoreResponse(array<string|int, mixed>|null $data) : mixed
You may override this method to do last-minute preparation before the response is sent.
Parameters
- $data : array<string|int, mixed>|null
-
an array of an additional data stored in a cache entry or
null
.
Tags
attach()
Attaches the behavior object to the component.
public
attach(mixed $owner) : mixed
Parameters
- $owner : mixed
-
the component that this behavior is to be attached to.
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.
public
beforeAction(Action $action) : bool
Parameters
- $action : Action
-
the action to be executed.
Return values
bool —whether the action should continue to be executed.
beforeCacheResponse()
This method is invoked right before the response caching is to be started.
public
beforeCacheResponse() : bool|array<string|int, mixed>
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
.
Tags
Return values
bool|array<string|int, mixed> —whether to cache or not, return an array instead of true
to store an additional data.
beforeFilter()
public
beforeFilter(ActionEvent $event) : mixed
Parameters
- $event : ActionEvent
cacheResponse()
Caches response properties.
public
cacheResponse() : mixed
Tags
canGetProperty()
Returns a value indicating whether a property can be read.
public
canGetProperty(string $name[, bool $checkVars = true ]) : bool
A property is readable if:
- the class has a getter method associated with the specified name (in this case, property name is case-insensitive);
- the class has a member variable with the specified name (when
$checkVars
is true);
Parameters
- $name : string
-
the property name
- $checkVars : bool = true
-
whether to treat member variables as properties
Tags
Return values
bool —whether the property can be read
canSetProperty()
Returns a value indicating whether a property can be set.
public
canSetProperty(string $name[, bool $checkVars = true ]) : bool
A property is writable if:
- the class has a setter method associated with the specified name (in this case, property name is case-insensitive);
- the class has a member variable with the specified name (when
$checkVars
is true);
Parameters
- $name : string
-
the property name
- $checkVars : bool = true
-
whether to treat member variables as properties
Tags
Return values
bool —whether the property can be written
className()
Returns the fully qualified name of this class.
public
static className() : string
Tags
Return values
string —the fully qualified name of this class.
detach()
Detaches the behavior object from the component.
public
detach() : mixed
events()
Declares event handlers for the [[owner]]'s events.
public
events() : array<string|int, mixed>
Child classes may override this method to declare what PHP callbacks should be attached to the events of the [[owner]] component.
The callbacks will be attached to the [[owner]]'s events when the behavior is attached to the owner; and they will be detached from the events when the behavior is detached from the component.
The callbacks can be any of the following:
- method in this behavior:
'handleClick'
, equivalent to[$this, 'handleClick']
- object method:
[$object, 'handleClick']
- static method:
['Page', 'handleClick']
- anonymous function:
function ($event) { ... }
The following is an example:
[
Model::EVENT_BEFORE_VALIDATE => 'myBeforeValidate',
Model::EVENT_AFTER_VALIDATE => 'myAfterValidate',
]
Return values
array<string|int, mixed> —events (array keys) and the corresponding event handler methods (array values).
getDynamicPlaceholders()
{@inheritdoc}
public
getDynamicPlaceholders() : mixed
getView()
{@inheritdoc}
public
getView() : mixed
hasMethod()
Returns a value indicating whether a method is defined.
public
hasMethod(string $name) : bool
The default implementation is a call to php function method_exists()
.
You may override this method when you implemented the php magic method __call()
.
Parameters
- $name : string
-
the method name
Return values
bool —whether the method is defined
hasProperty()
Returns a value indicating whether a property is defined.
public
hasProperty(string $name[, bool $checkVars = true ]) : bool
A property is defined if:
- the class has a getter or setter method associated with the specified name (in this case, property name is case-insensitive);
- the class has a member variable with the specified name (when
$checkVars
is true);
Parameters
- $name : string
-
the property name
- $checkVars : bool = true
-
whether to treat member variables as properties
Tags
Return values
bool —whether the property is defined
init()
Initializes the object.
public
init() : mixed
setDynamicPlaceholders()
{@inheritdoc}
public
setDynamicPlaceholders(mixed $placeholders) : mixed
Parameters
- $placeholders : mixed
calculateCacheKey()
protected
calculateCacheKey() : array<string|int, mixed>
Tags
Return values
array<string|int, mixed> —the key used to cache response properties.
getActionId()
Returns an action ID by converting [[Action::$uniqueId]] into an ID relative to the module.
protected
getActionId(Action $action) : string
Parameters
- $action : Action
Tags
Return values
stringisActive()
Returns a value indicating whether the filter is active for the given action.
protected
isActive(Action $action) : bool
Parameters
- $action : Action
-
the action being filtered
Return values
bool —whether the filter is active for the given action.
restoreResponse()
Restores response properties from the given data.
protected
restoreResponse(Response $response, array<string|int, mixed> $data) : mixed
Parameters
- $response : Response
-
the response to be restored.
- $data : array<string|int, mixed>
-
the response property data.
Tags
updateDynamicContent()
Replaces placeholders in $content with results of evaluated dynamic statements.
protected
updateDynamicContent(string $content, array<string|int, string> $placeholders[, bool $isRestoredFromCache = false ]) : string
Parameters
- $content : string
-
content to be parsed.
- $placeholders : array<string|int, string>
-
placeholders and their values.
- $isRestoredFromCache : bool = false
-
whether content is going to be restored from cache.
Return values
string —final content.
insertResponseCookieCollectionIntoData()
Inserts (or filters/ignores according to config) response cookies into a cache data array.
private
insertResponseCookieCollectionIntoData(Response $response, array<string|int, mixed> &$data) : mixed
Parameters
- $response : Response
-
the response.
- $data : array<string|int, mixed>
-
the cache data.
insertResponseHeaderCollectionIntoData()
Inserts (or filters/ignores according to config) response headers into a cache data array.
private
insertResponseHeaderCollectionIntoData(Response $response, array<string|int, mixed> &$data) : mixed
Parameters
- $response : Response
-
the response.
- $data : array<string|int, mixed>
-
the cache data.