Jul 1, 2014

Function cache_clear_all() has been removed

Drupal 8 has a new API for caching, so D7 functions such as cache_clear_all() have disappeared.

Function cache_clear_all() has a boolean third parameter that indicates use of a wildcard. If this third param is true, then the first param, which is the "cache_id", acts as though it has a trailing wildcard. That is, any cache IDs starting with the string value of  the cache_id param  are deleted in addition to the exact cache ID specified.

Unfortunately, that kind of wildcard functionality seems to be missing from the new cache API.

In one case, that didn't matter. For example,
cache_clear_all('*', 'cache_page', TRUE);
was easily replaced by
$cache = \Drupal::cache('render');
$cache->deleteAll();
On the other hand, the following call does not have an exact equivalent, where the $recursive variable can be either true or false. 
cache_clear_all($cid, 'cache_page', $recursive);
My replacement below is overkill when $recursive is true, but the performance hit may not be significant given the nature of the Optimizely module and how often it triggers cache clearing.

$cache = \Drupal::cache('render');
if ($recursive) {
  $cache->deleteAll();
}
else {
  $cache->delete($cid);
}
The D8 docs state that the render bin contains "cached HTML strings like cached pages and blocks". I am assuming that it therefore includes entries kept in the cache_page bin in D7, but I have not tested and confirmed this yet.

The new API has two different ways to clear the cache, which are to "delete" and to "invalidate". Cached entries that are invalidated are still potentially accessible, whereas deleted ones are completely removed. In our case, the entries should no longer be used at all, so I used the delete methods.

Update: Caching of pages has been properly re-implemented for the module. See post  Using Drupal 8 Cache Tags for Page Caching  


Sources:

function cache_clear_all
https://api.drupal.org/api/drupal/includes!cache.inc/function/cache_clear_all/7

Cache API
https://api.drupal.org/api/drupal/core%21core.api.php/group/cache/8.0.x

interface CacheBackendInterface
https://api.drupal.org/api/drupal/core!lib!Drupal!Core!Cache!CacheBackendInterface.php/interface/CacheBackendInterface/8

Drupal 8: perf & ops - Cache tags & pluggable asset optimization, Wim Leers
http://wimleers.com/talk-drupal-8-perf-ops/

2 comments:

  1. Do a site wide clear of the cache on recursive requests to a specific path is less than idea. I like your working solution but this will have to be revisited as it's a significant performance issue for larger sites - DoSomething.org being one of them.

    ReplyDelete
    Replies
    1. Let's definitely treat this as a red flag at the top of the list of open issues.

      Delete