如何向缓存

时间:2017-02-17 13:10:49

标签: php caching yii2

我在yii2框架中使用文件缓存 我的问题是
是否可以在不刷新cacheFile的情况下向缓存添加一些额外的值。我现在在每个条目上更新缓存文件为我的产品创建缓存文件。我想只添加新产品进行缓存 我怎么能提前谢谢你呢 这是我的代码

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

我编写了获取所有产品的商店程序,现在当我每次调用updateCache函数时都会添加新产品,该函数会重新生成产品并将其添加到缓存中,因为可能会影响应用程序的速度。
这是addingProductupdateCache的代码:

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

1 个答案:

答案 0 :(得分:2)

原生Yii2缓存组件不允许更新现有缓存项部分。 但您可以手动执行此操作:

public static function addToCache($modelProduct) {

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

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

但我推荐其他方式:您可以将每个产品记录存储为单独的缓存项目。 首先,您可以添加多个项目:

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

其次,您可以在读取数据时更新缓存。例如:

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

此代码仅为缓存中尚未出现的每个$id创建一次缓存。

第三,您可以在创建/更新之后将单个产品添加到缓存中。例如:

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

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

我认为这种方法更灵活。当然,它可能效率低于你的方式。它取决于读取缓存的代码。