Yii2: How to make a dependency cache from the value of a variable?

Let me explain the question. Want to make caching of news depending on their number. about there is a problem in that if to do through
$dependency = new \yii\caching\DbDependency(['sql' => "SELECT COUNT(*) FROM news"]);

and as I have above for the pager number is
$query = News::find();
$countQuery = $query->count();

I have two query in one place, almost counting the number of news. I would like to get rid of and addiction to pass $countQuery. How can I do that?
June 8th 19 at 17:21
2 answers
June 8th 19 at 17:23
$query = News::find();
$countQuery = $query->count();

$data = Yii::$app->cache->getOrSet('newsCacheKey', function () use ($query) {
 return $query->all();
}, $this->cacheDuration, new TagDependency([
 'tags' => [
 News::className() . $countQuery
]
]));
The cache is not flushed when you change the number of records - kiara.Leuschke commented on June 8th 19 at 17:26
the tags themselves have not cleaned their hands clean if the machine that my solution will not work, it is necessary hostility, but you have the essence of the cache is not right, because news can be updated and the cache is not reset, you have to rely on the time to news updates to the cache were normal and still 2 queries, I don't understand why you so afraid of, not the place where it is necessary to optimize - Mitchell_Zemlak16 commented on June 8th 19 at 17:29
I have a website communicates with 3 databases, all databases are on different servers and many different queries. The more you will reduce the page load time the better

after all, news can be updated

I think it's just to update the cache of the event... But will have to consider...

the tags themselves have not cleaned their hands clean if the machine that my solution will not work

So I will use TagDependency::invalidate(Yii::$app->cache, 'newsCacheKey'); ? How to get a value already stored in TagDependency? Or I not correctly understood the essence? - kiara.Leuschke commented on June 8th 19 at 17:32
June 8th 19 at 17:25
/yiisoft/yii2/caching/TagDependency.php
We'll see if it will fit
in the case of using the cache depending on the tags, you must manually reset the cache
TagDependency::invalidate(Yii::$app->cache, 'cache-key');
- Mitchell_Zemlak16 commented on June 8th 19 at 17:31
Maybe I just do not understand how to work with it, but when trying to use my cache was not reset, when the number of news updated. - kiara.Leuschke commented on June 8th 19 at 17:28

Find more questions by tags YiiCaching