Search code examples
zend-frameworkzend-cache

Patterns for clearing Zend Cache


I started using Zend Cache (APC backend) and all is well in terms of returning cached values instead of hitting the Database each time. However, heres my problem:

$cache_key = 'getrebates_'.$operator_code;

if(PP_Model_CacheService::exists($cache_key)) {
    $cached_values = PP_Model_CacheService::load($cache_key);
} else {
   //hits the db    
   $cached_values = $this->getAll($operator_code);
   PP_Model_CacheService::save($cached_values, $cache_key);
}
return $cached_values;

Each operator has their own rebates which vary between operators, now if I change the database and need to clear the rebates for all the operators, how would I do this?

I can use $Cache->clean(), but that will clear the other caches (not just the rebate cache for each operator). If I loop through all operators:

foreach($operator_codes AS $operator_code) {
   $cache_key = 'getrebates_'.$operator_code;
   $cache->delete($cache_key)
}

That seems like alot of work for the cache. Is there a way to clear just a section of Cache.

//Something like:
$section_key = 'getrebates';
$Cache[$section_key][$operator_code];
$Cache->clearSection($section_key);

Is there any array structure to the APC cache or is it all cache key/value based?


Solution

  • You can apply tags to values stored in the cache. That way you can easily delete all cache entries which have a certain tag.

    $cache->save($huge_data, 'myUniqueID', array('tagA', 'tagB'));
    
    // clear all cache entries with tag tagA or tagC
    $cache->clean(
      Zend_Cache::CLEANING_MODE_MATCHING_TAG,
      array('tagA', 'tagC')
    );
    

    Refer to this page: http://framework.zend.com/manual/en/zend.cache.theory.html and the API for details about the clean method of Zend_Cache_Core: http://framework.zend.com/apidoc/1.11/