How to clear db request cache in yii2?

How to handle it when some changes occur in specific table entries?

public static function getAirportWithCache($iata_code){

              $result = Airports::getDb()->cache(function ($db) use ($iata_code){
                     $res = Airports::find()
                               ->where(['iata_code' => $iata_code])
                               ->limit(1)
                               ->asArray()
                               ->one();
                     return $res;
              });
              return $result;
        }
+4
source share
3 answers

For the global cache, you can use:

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

for spesific you can use TagDependency:

 //way to use
return Yii::$app->db->cache(function(){
    $query =  new Query();
    return $query->all();
}, 0, new TagDependency(['tags'=>'cache_table_1']));

//way to flush when modify table
TagDependency::invalidate(Yii::$app->cache, 'cache_table_1');

see documentation http://www.yiiframework.com/doc-2.0/yii-caching-tagdependency.html

+4
source

You should just use \yii\caching\DbDependency, for example.

public static function getAirportWithCache($iata_code){
    // for example if airports count change, this will update your cache
    $dependency = new \yii\caching\DbDependency(['sql' => 'SELECT COUNT(*) FROM ' . Airports::tableName()]);
    $result = Airports::getDb()->cache(function ($db) use ($iata_code){
        return Airports::find()
            ->where(['iata_code' => $iata_code])
            ->limit(1)
            ->asArray()
            ->one();
    }, 0, $dependency);
    return $result;
}

More details ...

+3
source

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

PS: ,

0

Source: https://habr.com/ru/post/1627786/


All Articles