Table of Contents

Cache

Moodle 2.4 saw the introduction of the MUC: Moodle Universal Cache. The cache is actually comprised of a number of smaller caches, defined in /lib/db/caches.php and the caches.php files of the various plugins (e.g. mod/yourmod/db/caches.php).

See the Cache API and the Quick reference. The most succinct overview is in Moodle's github repo.

How to Use The Cache

In your plugin, create a file db/caches.php:

$definitions = array(
    'labelcontent' => array(
        'mode' => cache_store::MODE_APPLICATION,
        'simplekeys' => true, // keys limited to a-zA-Z0-9_ (better performance)
        'simpledata' => true, // data type limited to scalar (e.g. strings, integers) or array of scalars
    )
);

Now you're ready to use the cache in your code. Use the current language as part of your key:

    $cache = cache::make('mod_my_plugin', 'labelcontent');
    // Compose the cache key, e.g. based on the instance id of your plugin
    $key = current_language() . $id;
    if (!$data = $cache->get($key)) {
        // Data was not cached yet, so retrieve:
        $data = $DB->get_record('mdl_my_plugin_some_table', array('id' => $id));
        $cache->set($key, $data);
    }
    return $data;

Invalidate Cache

Delete Cache by Key

To delete a cache, you first have to retrieve the cache, using a make function ('make' denotes the activity of using a class factory, not the making of a cache). Then, using the cache object, you can call the delete method.

// Delete the cache, for caching issue with groups
$cache = cache::make('core', 'groupdata');
$cache->delete($enrollment->courseid);

How do you know which id you can use as the parameter for cache#delete? If you created the cache key yourself, then you use that key of course:

$cache->delete(current_language() . $id);

For other cases it looks as though it's defined in the lib/db/caches.php file. For instance, for groupdata, the definition is:

// Groupings belonging to a course.
// A simple cache designed to replace $GROUPLIB_CACHE->groupings.
// Items are organised by course id and are essentially course records.
'groupdata' => array(
    'mode' => cache_store::MODE_APPLICATION,
    'simplekeys' => true, // The course id the groupings exist for.
    'simpledata' => true, // Array of stdClass objects containing only strings.
    'staticacceleration' => true, // Likely there will be a couple of calls to this.
    'staticaccelerationsize' => 2, // The original cache used 1, we've increased that to two.
),

Invalidate Cache by Definition

The other method to delete a cache, is by using the cache_helper::invalidate_by_definition method:

cache_helper::invalidate_by_definition('core', 'databasemeta', array('dbfamily' => $DB->get_dbfamily()));

If you're ever want to modify the database through your mod's install.php file, you're going to need this helper!