8

How to handle it when some changes happen in specific table records ?

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;
        }
Yatin Mistry
  • 1,246
  • 2
  • 13
  • 35

3 Answers3

14

For global cache, 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 the documentation http://www.yiiframework.com/doc-2.0/yii-caching-tagdependency.html

4

You should simply use \yii\caching\DbDependency, e.g. :

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;
}

Read more...

soju
  • 25,111
  • 3
  • 68
  • 70
  • 1
    This should be accepted as the answer as it is the correct solution according to yii2-specs! – PLM57 Feb 09 '16 at 08:59
  • I thought of doing this but how does Yii know when the data has changed? To know wouldn't it have to do a query to find out and hence defeat the purpose of caching in the first place!? – Brett Oct 25 '16 at 19:27
2

Just execute Yii::$app->cache->flush(); anywhere (probably in your controller)

PS: It will delete entire cache stored in your server

Sohel Ahmed Mesaniya
  • 3,344
  • 1
  • 23
  • 29
  • I will check. and how to handle if any changes happen in table specific record? – Yatin Mistry Feb 08 '16 at 12:25
  • Also this will remove my whole caching. i want to specific for db queries. – Yatin Mistry Feb 08 '16 at 12:31
  • 4
    This definitely is not the solution, as it will flush your whole cache. This means query-cache, rbac-cache, schema-cache about everything except if you had multiple cache-components attached... – PLM57 Feb 09 '16 at 08:58