Yii 2 Caching

Caching in Yii 2

Content of the «Caching» section:

Articles section «Caching»:

HTTP Caching in Yii 2

HTTP Caching

Besides server-side caching that we have described in the previous sections, Web applications may also exploit client-side caching to save the time for generating and transmitting the same page content.

To use client-side caching, you may configure [[yii\filters\HttpCache]] as a filter for controller actions whose rendering result may be cached on the client-side. [[yii\filters\HttpCache|HttpCache]] only works for GET and HEAD requests. It can handle three kinds of cache-related HTTP headers for these requests:

Page Caching in Yii 2

Page Caching

Page caching refers to caching the content of a whole page on the server-side. Later when the same page is requested again, its content will be served from the cache instead of regenerating it from scratch.

Page caching is supported by [[yii\filters\PageCache]], an action filter. It can be used like the following in a controller class:

Fragment Caching in Yii 2

Fragment Caching

Fragment caching refers to caching a fragment of a Web page. For example, if a page displays a summary of yearly sale in a table, you can store this table in cache to eliminate the time needed to generate this table for each request. Fragment caching is built on top of data caching.

Data Caching in Yii 2

Data Caching

Data caching is about storing some PHP variables in cache and retrieving it later from cache. It is also the foundation for more advanced caching features, such as query caching and page caching.

The following code is a typical usage pattern of data caching, where $cache refers to a cache component:

Caching Overview in Yii 2


Caching is a cheap and effective way to improve the performance of a Web application. By storing relatively static data in cache and serving it from cache when requested, the application saves the time that would be required to generate the data from scratch every time.