简体   繁体   中英

Can not delete cached item created with beginCache

I have a fragment that I'm caching because there are a lot of database hits to generate the content.

main.php:

    'cache'=>array(
            'class'=>'system.caching.CFileCache'
    )

view.php

<?php if($this->beginCache("my_id", array('duration' => 315360000))) { ?>
   // lots of heavy stuff
<?php $this->endCache(); } ?>

My cached fragment only changes when I adjust the configuration in a database table. I'm trying to find a way to delete the cached item using the "my_id". The Yii documentation is somewhat misleading because when it talks about beginCache it refers to the key ("my_id"), but when it talks about deleting items from the cache it also talks about the key, but it is not the same key! beginCache is essentially a wrapper for an COutputCache widget and so "my_id" is not the key used in the cache.

Does anyone know how to convert "my_id" into a cache-friendly key so that I can delete that specific item from the cache.

I've tried extending from CFileCache but my key is generated from COutputCache which uses CFileCache and I don't think there is a back route. I have also tried beginning a widget with an overloaded version of COutputCache which works but just seems like a really nasty hack.

    $properties = array();
    $properties['id']=Yii::app()->params["cache_name_matrix"];
    $cache=$this->beginWidget('MyCOutputCache',$properties);
    $key = $cache->getKeyHack();

My current work around is flush the whole cache but this gets rid of everything and seems a little bit heavy handed.

Any ideas?

COutputCache calculates the cache key using protected method called getCacheKey which internally calls getBaseCacheKey and then depending on specified variations transforms it. In your, the simplest case, with no variations, I believe it will end up with something like 'Yii.COutputCache.my_id.......' where 'Yii.COutputCache.' is COutputCache::CACHE_KEY_PREFIX. Take a look at the code of this method.

So, knowing this, you technically can delete your fragment manually. But I strongly encourage you to take a look at mechanism of dependencies described in the manual . You said you invalidate this fragment if something changes in your database, so probably CDbCacheDependency is what you need.

Yii2 try this

$key = Array ('yii\widgets\FragmentCache','key_id');
Yii::$app->cache->delete($key);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM