Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to invalidate / dirty Yii2 query cached record?

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.

like image 360
Oleg Planovoy Avatar asked Dec 30 '25 06:12

Oleg Planovoy


1 Answers

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.

like image 71
lgomezma Avatar answered Jan 01 '26 19:01

lgomezma



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!