1

What is the right way to construct and update my key/value with dataProvider when the database is updated ? First i am finding all of the news from database. How should i add or update the value of my key/value pair ? I always have and never catch the block with query. Red a lot of materials but didn't find the right way.

$mem = new \Memcached();
$mem->addServer("localhost", 11211);
$result = $mem->get('categoriesProvider');

if(!$result){
    $whereString = " active = 1 ";
    $categoriesProvider = new ActiveDataProvider([
         'query' => News::find()->where($whereString),
         'pagination' => [
         'pageSize' => 6,
         'route' => Yii::$app->getRequest()->getQueryParam('first_step'),
                ],
         ]);
 $mem->set("categoriesProvider", $categoriesProvider);
 }
 $result = $mem->get("categoriesProvider");

Here is my view :

echo ListView::widget([
     'dataProvider' => $result,
     'itemView' => '_blogCategories',
     'layout' => '{items}<ulclass="pagination theme-colored">{pager}</ul>',
     'pager' => [
     'maxButtonCount' => 3,
     'options' => ['class' => 'pagination flRight'],
      ],

]);

Jeni Vasileva
  • 768
  • 6
  • 26

1 Answers1

4

As memcached and yii2 user myself I can suggest you to put the cache between data and provider, the simplest way is to query for data you need then cache results in the most lightweigth form (as an array of items where items are array themselves), then, use it to show your data or pass to a provider that can show your data.

The YII2 interface for Memcached allows you to take advantage of the new method getOrSet() where you can use a callback which produces data to be cached if it's not present already, hence relieving you the burden to craft such flow yourself.

It is not generally a good idea to store in cache an instance of a complex object as the ones in YII2.

nicola.p
  • 66
  • 1
  • 3