Dani
Dani

Reputation: 925

How to add values to cache

I am using file cache in yii2 framework.
My question is
Is it possible to add some extra value to cache without refresh the cacheFile.Suppose i create cache file for my products now on each entry i update cache file. I want to add just the new product to cache.
How can i do that thanks in advance
This is my Code

public static function updateCache(){
    $product_grid = Yii::$app->db->createCommand("CALL get_products()")->queryAll();
    Yii::$app->cache->set('product_grid', $product_grid);
}

I write store procedure for getting all products,now when i add new product each time i am calling the updateCache function which regenerate the products and add it to cache due to which application speed may be effected.
This is the code for addingProduct and updateCache:

public function actionCreate($id = NULL) {
    $model = new PrProducts();
    if ($model->load(Yii::$app->request->post())) {
        $model->save(false);
        self::updateCache();
    }
}

Upvotes: 1

Views: 1211

Answers (1)

IStranger
IStranger

Reputation: 2041

Native Yii2 cache components doesn't allow to update existing cache items partially. But you can do this manually:

public static function addToCache($modelProduct) {

    $productGrid                    = Yii::$app->cache->get('productGrid');
    $productGrid[$modelProduct->id] = $modelProduct->attributes;

    Yii::$app->cache->set('productGrid', $productGrid);
}

But I recommend other way: you can store each product record as separate cache item. Firstly you can add multiple items:

public static function refreshProductCache() {

    // Retrieve the all products
    $products = Yii::$app->db->createCommand("CALL get_products()")->queryAll();

    // Prepare for storing to cache
    $productsToCache = [];
    foreach ($products as $product) {
        $productId                                = $product['id'];
        $productsToCache['product_' . $productId] = $product;
    }

    // Store to cache (existing values will be replaced)
    Yii::$app->cache->multiSet($productsToCache);
}

Secondly you can update cache when you read data. For instance:

public function actionView($id) {

    $model = Yii::$app->cache->getOrSet('product_'.$id, function() use ($id) {
        return PrProducts::find()
            ->andWhere(['id' => $id])
            ->one();
    });

    return $this->render('view', ['model' => $model]);
}

This code creates cache only one time for each $id that not yet present in the cache.

Thirdly you can add individual products to cache right after create/update. For instance:

public static function addToCache(PrProducts $modelProduct) {
    $productId = $modelProduct->id;

    Yii::$app->cache->set('product_' . $productId, $modelProduct);
}

I think this approach more flexible. Of course, it may be less efficient than you way. It very depends from code that reads your cache.

Upvotes: 2

Related Questions