2

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?

1 Answer 1

2

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);
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks @rob006 that works perfectly. Good to know that ArrayCache is explicitly designed for this.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.