I have a custom module in Drupal 7 where I am caching data from REST calls using drupal_static() and cache_set().

function _mymodule_call() {
  $data = &drupal_static(__FUNCTION__);
  if ( ! isset($data) ) {
    if ($cache = cache_get(__FUNCTION__)) {
      $data = $cache->data;
    else {
      $data = my_api_call();

      if ( is_object($lists) ) {
        // cache for one hour
        cache_set(__FUNCTION__, $data, 'cache', time() + 3600);
  return $data;

I want to make an admin feature where we can specifically clear these cached values. I suppose the cache key would be _mymodule_call. How do I clear them from the cache?


The Drupal way is to have a $reset parameter to your function. It would look something like:

function _mymodule_call($reset = FALSE) {
  if ($reset) {
    // do stuff
  // ...

node_load() is probably the best example of this.

In your specific case, you can pass the $reset parameter to drupal_static() or explicitly call drupal_static_reset(). For the cache backend, you need to think whether you want to just rework the logic and just do the cache_set() or explicitly call cache_clear_all($cid) (my guess is the former).

And remember, that drupal_static() is only effective when you need the value multiple times during the same request. This does not persist between page loads (or any other HTTP request that get handled by Drupal).

  • cache_clear_all($cid) -- in my case, would that be cache_clear_all('_mymodule_call')?
    – user1359
    Dec 28 '16 at 1:41
  • @user1359 Looks like it would be cache_set(__FUNCTION__, 'cache'); the $bin needs to be specified when you use the $cid. Check out the API page.
    – mpdonadio
    Dec 28 '16 at 4:40

I made a test script, and it turns out that in my code above, _mymodule_call is the $cid, because I created my cache in the _mymodule_call function like so: cache_set(__FUNCTION__, $data, 'cache', time() + 3600);.

Thanks to mpdonadio for noting that you have to specify the $bin argument when you use cache_clear_all(). In my case, since I wasn't specifying it in cache_set(), it defaults to 'cache'.

Here's my script:

$> cat cache_test.php
// set the cache
cache_set('test_key', 'hello there ' . mt_rand(), 'cache');
$data = cache_get('test_key');
// display it
// clear it
cache_clear_all('test_key', 'cache');
// retrieve it (should be empty)
$data = cache_get('test_key');
// display the emptied(?) cache

And here's its output:

$> drush scr cache_test.php
stdClass Object
    [cid] => test_key
    [data] => hello there 1718114879
    [created] => 1482938803
    [expire] => 0
    [serialized] => 0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.