Sunday, 8 November 2015

Drupal caching using cache_get and cache_set

Drupal functions cache_get and cache_set are basically used for static caching temporarly and permanently in the cache table of the drupal database.
Using cache_set function is fairly simple below is a syntax of how you can implement this.
cache_set(key, value, 'cache', CACHE_TEMPORARY); or cache_set(key, value, 'cache', CACHE_PERMANENT); 
cache_set takes four parameters first the key parameter, this parameter is unique for the system and is used to differentiate between other records in the table also this key is used to retrive data from the database the second parameter is the value that is the data to be stored in the key.
Now the third parameter is the table name that is table to store the data in and the fourth parameter is the cache type that is temporary or permanent, if temporary it will flush the cache when the cron runs and if permanent cache type is selected the cache will never expire.
cache_get function is used to retrive the data from the cache table based on the key in the table. Below is the syntax of how you can implement this.
cache_get(key);
The cache_get function when invoked by a key returns an object which contains the cache id as cid the value as the data variable and the expire that is the time it will expire. If expire is set to zero the cache will never expire. Below is a full syntax of how this is implemented.
  $tempdata =  cache_get('cachekey');
  if(isset($tempdata->data)) {
    return $tempdata->data;
  } else {
    $value = "Test Cache Value";
    cache_set('cachekey', $value, 'cache', CACHE_TEMPORARY);
    return $value;
  }

No comments:

Post a Comment