How To Use Caching with the Yii Framework for Improving Performance

Yii framework offers a number of features, an important one being a cache management system. It permits saving both your SQL/Active Record queries and static data that can aid in saving a great amount of page loading time if used carefully.

In this guide, we will learn caching of Queries and Data.

Given below is the procedure for enabling cache in Yii.

Activating the Cache Component

The first step involves activation of the cache component. Firstly, open your configuration file that resides within protected/config/, navigate to the components array, and then type in the code given below right in the array:


With this, we are opting for utilization of CDbCache that is among different Caching Components accessible in Yii. CDbCache utilizes  SQLite database for storing the cached data and this enables set up to be done very easily.  Although it’s not the wisest option when considering performance, but still our web application would become a bit faster because of it.

CApcCache component that utilizes APC, the in-built caching system available with the most advanced PHP versions, is another robust and practical choice.

Just by switching the component’s name, like system.caching.CApcCache, one can simply shift from one cache component to the other, without the need to change any code in an application, as all the Cache components mentioned above are built upon on top of the CCache class.

Simple Data Caching

The easiest and first method of using cache is through storing variables. For doing that, cache component of Yii provides you with two functions- get() and set().

Now we begin by fixing a value for caching. For doing this, we also need to provide a unique ID to it. For instance:

// Storing $value in Cache
$value = "This is a variable that I am storing";
$id    = "myValue";
$time  = 30; // in seconds

Yii::app()->cache->set($id, $value, $time);

$time, the last value given above is not needed, though it finds usage in avoiding forever storing a value in case it is not essential.

Obtaining the stored value is almost irrelevant:


If  the value is not found  (in case it expired before or it did not exist), then a false value will be returned by this function. Therefore, for instance, a simple method of finding out if a specific value is cached or not would be:

$val = Yii::app()->cache->get($id);
if (!$val):
    // the value is not cached, do something here
    // the value is cached, do something else here

Delete a cached value

For deleting a value which is residing in cache, the function given below can be called:


In order to clean everything, we need to simply write:


Query Caching

This feature built upon top of the Data Caching system is an extremely beneficial feature, specially for those heavy apps that strongly depend upon a Database.

This feature is not only very easy but is also fairly solid.

First of all, we have to describe a dependency query . Simply stated, we will be defining a very light and simple Database Query which will be called prior to the one that is really needed. This is done for checking in case something has changed since the last time that query was executed.

For instance, if we intend to obtain the data pertaining to an Authors’ list, then our dependency query can be as follows:

SELECT MAX(id) FROM authors

With this, it can be checked if any new author was added or not from the time we last checked. In case no author was added to the list then cache component of Yii will fetch the list of Authors directly from the cache, without running our big query again, that would look something like below:

SELECT authors.*, book.title 
FROM authors 
JOIN book ON = authors.book_id

Yii Query Builder

For using Query Caching through the Yii Query Builder, we need to write query as given below [Authors’ example shown above has been used in this case]:

// big query
$query = ' SELECT authors.*, book.title 
FROM authors 
JOIN book ON = authors.book_id';
// dependency query 
$dependency = new CDbCacheDependency('SELECT MAX(id) FROM authors'); 
// executing query using Yii Query Builder
$result = Yii::app()->db->cache(1000, $dependency)->createCommand($query)->queryAll();

The arguments that are passed onto Yii::app()->db->cache() are the amount of seconds for which the results should be saved and the dependency query respectively.

As mentioned previously, during operating this piece of code, Yii will first look into the dependency query’s result prior to anything else. If it finds a dissimilar value than the one stored previously then the big query will be executed by Yii and its result would be stored in cache or if it doesn’t find anything at all, then the result of the big query will be extracted from the cache.

Active Record

Additionally, it is possible for caching a query’s result that’s made by utilizing Active Record. There’s a change in the syntax only and the concept remains exactly the same as previously explained:

$dependency = new CDbCacheDependency('SELECT MAX(id) FROM authors');
$authors = Author::model()->cache(1000, $dependency)->with('book')->findAll();

Things to be kept in mind

Applications that utilize caching extensively needs to be designed well in advance as the possibility of providing user with inconsistent data will surely increase.

Furthermore, every caching component may have limitations on the amount of data which can be saved. So a good practice would be to find out the limitation of your caching system well in advance.

KB Admin has written 28 articles

Leave a Reply