Caching

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, we save the time needed to generate the data.

Using cache in Yii mainly involves configuring and accessing a cache application component. The following application configuration specifies a cache component that uses memcache with two cache servers.

array(
    ......
    'components'=>array(
        ......
        'cache'=>array(
            'class'=>'system.caching.CMemCache',
            'servers'=>array(
                array('host'=>'server1', 'port'=>11211, 'weight'=>60),
                array('host'=>'server2', 'port'=>11211, 'weight'=>40),
            ),
        ),
    ),
);

When the application is running, the cache component can be accessed via Yii::app()->cache.

Yii provides various cache components that can store cached data in different media. For example, the CMemCache component encapsulates the PHP memcache extension and uses memory as the medium of cache storage; the CApcCache component encapsulates the PHP APC extension; and the CDbCache component stores cached data in database. The following is a summary of the available cache components:

Tip: Because all these cache components extend from the same base class CCache, one can switch to use a different type of cache without modifying the code that uses cache.

Caching can be used at different levels. At the lowest level, we use cache to store a single piece of data, such as a variable, and we call this data caching. At the next level, we store in cache a page fragment which is generated by a portion of a view script. And at the highest level, we store a whole page in cache and serve it from cache as needed.

In the next few subsections, we elaborate how to use cache at these levels.

Note: By definition, cache is a volatile storage medium. It does not ensure the existence of the cached data even if it does not expire. Therefore, do not use cache as a persistent storage (e.g. do not use cache to store session data).