Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to clear cache in yii2 AR?

Tags:

yii2

How to clear that cache of current data?

$result = Customer::getDb()->cache(function ($db) use ($id) {
    return Customer::findOne($id);
}, 60 * 60 * 24 * 4);

I want to clear the cache of current data in Customer after updating

like image 311
lolka Avatar asked May 22 '17 04:05

lolka


2 Answers

You can modify this code to use data cache instead of query cache so you can use unique key.

$data = $cache->get('customer' . $id);
if ($data === false) {
    $data = Customer::findOne($id);
    $cache->set('customer' . $id, $data, 60 * 60 * 24 * 4);
}

or starting from 2.0.11:

$data = $cache->getOrSet('customer' . $id, function () use ($id) {
    return Customer::findOne($id);
}, 60 * 60 * 24 * 4);

So now you can use

$cache->delete('customer' . $id);
like image 166
Bizley Avatar answered Dec 04 '22 00:12

Bizley


you can use flush for global.

Yii::$app->cache->flush();

you can use TagDependency :

$result = Customer::getDb()->cache(function ($db) use ($id) {
    return Customer::findOne($id);
}, 60 * 60 * 24 * 4, new TagDependency(['tags'=>'customer']));

//to flush
TagDependency::invalidate(Yii::$app->cache, 'customer');

For more information check here

like image 42
lalithkumar Avatar answered Dec 04 '22 01:12

lalithkumar