Reputation: 1662
I am using memcached as cache component for my Yii2 application. Background is that I am having a rather complex GridView component that often calls a function of the associated model counting some relations. Some of these functions are called rather often (once to display and multiple times again to evaluate which action columns should be shown.
The challenge now is that I want to cache the value, but only for the unique request and not for any given period of time as the list is rather often refreshed. The code examples below are from the model.
First try was just to use the cache with a short duration as follows. This however does not seem to work. Even after minutes the value is not refreshed until I remove the enclosing cache commands.
public function getRelationCount()
{
return Yii::$app->cache->getOrSet('wc_'.$this->id.'_cc', function () {
return $this->getRelationss()->count();
}, 5);
}
Second try was to add an ExpressionCondition
to identify the request, but I was unable to find a condition which identifies the request and not the session. For the session its rather easy:
public function getCompetitorCount()
{
$dependency = new ExpressionDependency(['expression' => 'Yii::$app->session->getId();']);
return Yii::$app->cache->getOrSet('wc_'.$this->id.'_cc', function () {
return $this->getCompetitors()->count();
}, 30, $dependency);
}
Any idea how to cache the value for the request only?
Upvotes: 2
Views: 513
Reputation: 22174
You need ArrayCache
:
ArrayCache provides caching for the current request only by storing the values in an array.
Configure it as separate component:
'requestCache' => [
'class' => ArrayCache::class,
],
And use it instead of Yii::$app->cache
:
return Yii::$app->requestCache->getOrSet('wc_'.$this->id.'_cc', function () {
return $this->getRelationss()->count();
}, 5);
Upvotes: 2