Cache Set, Get and Invalidate per User in Drupal 7

Read Article
Pause
Resume
Stop
Cache Set, Get and Invalidate per User in Drupal 7

How to Set, Get and Invalidate the caches per user in Drupal 7, this blog article will explain a brief of how to do such implementation on Drupal using the default drupal cache functions.

Here, we go with the steps

  • Initially, create the custom functions for Get, Set and Invalidate the caches per user.
  • Here, cache id per user is pretty important, where user id or user email id will used as part of cache id.
  • And these functions should be used as when required for caching the page.
  • Their will be cases like, Caches should be Invalidated on some actions for that particular user. These can be covered with these below functions.

Here's the functions which are used to Get, Set and Invalidate caches.

<?php

function _get_cache($cache_id) {
    $cache = cache_get($cache_id);
    if (isset($cache_id) && REQUEST_TIME < $cache->expire) {
        return $cache->data;
    }
    else {
        return NULL;
    }
}

function _set_cache($cache_id, $data) {
    cache_set($cache_id, $data, 'cache', REQUEST_TIME + (60 * 60));
}

function _invalidate_cache($cache_id) {
    $cache = cache_get($cache_id);
    if (isset($cache) && !empty($cache)) {
        cache_clear_all($cache->cid, 'cache');
    }
}

Here's the function where we Set the cache on page load, if at all already cache doesn't exist for this cache id.

function sample() {
    global $user;
    $cache_id = $user->uid . "_sample";
    $cache_data = _get_cache($cache_id);
    if ($cache_data == NULL) {
        $cache_data = array();
        // Here processed data should be cached
        $data = getData();
        $cache_data['data'] = $data;
        _set_cache($cache_id, $cache_data);
    }
    return $cache_data;
}

Here's the function used to Invalidate the caches, on some particular actions of the particular user.

$cache_id = $user->id . "_sample";
_invalidate_cache($cache_id);

Advantages of having the caches enabled for few pages, The page load time will be reduced..

Cheers :)

Comments

Scroll to Top
We Need Your Consent
By clicking “I Accept Cookies”, you agree to the storing of cookies on your device to enhance site navigation & analyze site usage.
I Accept Cookies