Yii2 : how to cache active data provider?

十年热恋 提交于 2019-12-02 23:39:34

It has little use caching the data provider after instantiating, since it's not actually doing any selecting on the database until it has been prepared. So you would actually be caching an empty object instance like it is now.

If you have a very large set of records, call the dataProviders' prepare() in advance in the cache:

 self::getDb()->cache(function ($db) use ($dataProvider) {
     $dataProvider->prepare();
 }, 3600, $dependency);
 return $dataProvider;

This will actually cache whatever queries the dataProvider runs ,so the next time they will be fetched from the query cache. This should result in what you are looking for.

If you have a finite amount of records, caching them all at once could also work:

$key = 'MyCachedData'; // + Data uniquely referring to your search parameters
$cache = \Yii::$app->cache;
$dataProvider = $cache->get($key);
if (!$dataProvider) {
   $dependency = \Yii::createObject([
      'class' => 'yii\caching\DbDependency',
      'sql' => 'SELECT MAX(updated_at) FROM post',
   ]);

   $dataProvider = new \yii\data\ArrayDataProvider;
   $dataProvider->allModels = $query->all();
   $cache->set($key, $dataProvider, 3600, $dependency) 
} 
return $dataProvider;

Obviously this is less than ideal for larger datasets, but it depends on what you are looking for.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!