Reputation: 41
I am using latest (March 2016) Yii2's query caching mechanism in Models with Redis in a form:
$object = $db->cache(function ($db) use($id) {
return self::findOne($id);
});
As a result, an entry with GUID ID (e.g. "bb83d06878206d758eda3e29082dda4f") is set that holds the result of the query.
Is there a way to invalidate just that record (based on id) or the whole Model's table, every time Model's save method is invoked?
E.g. if a User record is saved, we want to dirty that User's record (or "user" table), so next time we fetch that user, cache is no longer valid and record is retrieved from DB.
If possible, I would like to avoid DbDependency (e.g. on "last_updated" field on the record), since that is another DB query, if I am not mistaken.
Upvotes: 3
Views: 646
Reputation: 1637
It seems that the way to go is to use TagDependency. With that tag you can invalidate the cached query when you see fit.
You create the cached query giving it a unique tag like this:
$object = $db->cache(function ($db) use($id) {
return self::findOne($id);
}, 0, new TagDependency(['tags' => 'myquerytag']));
Then when you want to invalidate it you can use the 'invalidate' static method of TagDependency like this:
TagDependency::invalidate(Yii::$app->cache, 'myquerytag');
Keep in mind that in this case I gave a cache expiration time of 0 for this query like in the documentation example, but you can give it any time you see fit.
Upvotes: 1