Google News
logo
Yii framework - Interview Questions
What is Data Caching in Yii framework?
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 :
// try retrieving $data from cache
$data = $cache->get($key);

if ($data === false) {
    // $data is not found in cache, calculate it from scratch
    $data = $this->calculateSomething();

    // store $data in cache so that it can be retrieved next time
    $cache->set($key, $data);
}
// $data is available here
 
Since version 2.0.11, cache component provides getOrSet() method that simplifies code for data getting, calculating and storing. The following code does exactly the same as the previous example:
$data = $cache->getOrSet($key, function () {
    return $this->calculateSomething();
});
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 :
$user_id = 42;
$data = $cache->getOrSet($key, function () use ($user_id) {
    return $this->calculateSomething($user_id);
});
Advertisement