Special Topics - Setting Up Data Caching

Data caching allows storing some PHP variables in cache and retrieving it later from this cache. It is also gives you possibility for more advanced caching features, such as query caching etc.

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

// Try to retrieve $data from cache
$data = CSessionCache::get($key);
    // $data is not found in cache or empty, so calculate it from scratch
    $data = Model::model()->doSomething();

    // Now store $data in cache so it can be retrieved next time
    CSessionCache::set($data, $key);

Since version 1.2.2, cache helper provides getOrSet() method that simplifies code for data getting, calculating and storing. The following code does exactly the same as the previous example:
// Try to retrieve $data from cache
$data = CSessionCache::getOrSet($key, function(){
    return Model::model()->doSomething();

When cache has data associated with the $key, the cached value will be returned. Otherwise, the passed anonymous function will be executed to calculate the value that will be cached and returned.

If the anonymous function requires some data from the outer scope, you can pass it with the use statement. For example:
// Try to retrieve $data from cache
$data = CSessionCache::getOrSet($key, function() use ($memberId){
    return Model::model()->doSomething($memberId);