V
V
Vlad2017-02-24 12:53:44
Yii
Vlad, 2017-02-24 12:53:44

Why is Yii2 not finding the cache?

There is an application. At certain moments, a cache of some selection from the database is created:

public static function getAllHosts($by = 'id')
{
  $_cache = Yii::$app->cache;		
  $key_cache_list_hosts = 'list_hosts_array_' . $by;
  $dependency = new \yii\caching\DbDependency(['sql' => 'SELECT COUNT(*) FROM {{%hosts}}']);
  
  $_hosts = $_cache->get($key_cache_list_hosts);
  
  if ($_hosts === false) {
    try {
      $_hosts = static::find()->asArray()->indexBy($by)->all();
    } catch (\Exception $e) {
      echo "\n\nFatal error in function <Hosts/getAllHosts>!\n{$e->getMessage()}\nEnd...\n";
      exit;
    }
    
    $_cache->set($key_cache_list_hosts, $_hosts, 3600 * 12, $dependency);
  }
  
  return $_hosts;
}

There is also a code responsible for deleting this cache:
public static function deleteAllKeyHosts()
{
  $_cache = Yii::$app->cache;
  $key_cache = [];
  $pref = 'list_hosts_array_';
  
  $key_cache[] = $pref . 'id';
  $key_cache[] = $pref . 'name';
  $key_cache[] = $pref . 'comment';
  
  foreach ($key_cache as $_key) {
    $_cache->delete($_key);
  }
}

Now about the main thing. While the application is running, if you create the mentioned cache and immediately call the delete function, then everything works without any complaints. But if the cache was created during one request to the application, and then another request requests the application to delete this cache, then Yii2 does not find these keys, although they are in the @app/runtime/cache folder. Question: how can this be?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
V
Vlad, 2017-03-13
@progress_man

The question is closed! After a long study of the problem, I found out that the cant is mine - the application had a module that used a separate config, and in it the application id was different from the "main" one...

M
Maxim Timofeev, 2017-02-24
@webinar

Based on your code, this is quite possible
. You are deleting the cache with three keys, one of them may not be. Add an existence check before deletion.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question