Search moodle.org's
Developer Documentation

See Release Notes

  • Bug fixes for general core bugs in 3.10.x will end 8 November 2021 (12 months).
  • Bug fixes for security issues in 3.10.x will end 9 May 2022 (18 months).
  • PHP version: minimum PHP 7.2.0 Note: minimum PHP version has increased since Moodle 3.8. PHP 7.3.x and 7.4.x are supported too.

Differences Between: [Versions 310 and 400] [Versions 310 and 401] [Versions 310 and 402] [Versions 310 and 403]

Cache loaders This file is part of Moodle's cache API, affectionately called MUC. It contains the components that are required in order to use caching.

Copyright: 2012 Sam Hemelryk
License: http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
File Size: 2278 lines (94 kb)
Included or required:0 times
Referenced: 0 times
Includes or requires: 0 files

Defines 4 classes

cache:: (45 methods):
  make()
  make_from_params()
  __construct()
  set_loader()
  set_data_source()
  set_is_sub_loader()
  set_identifiers()
  handle_invalidation_events()
  get()
  get_many()
  set()
  unref()
  requires_serialisation()
  deep_clone()
  set_many()
  has()
  has_all()
  has_any()
  delete()
  delete_many()
  purge()
  parse_key()
  has_a_ttl()
  store_supports_native_ttl()
  get_definition()
  get_store()
  get_loader()
  get_datasource()
  store_supports_key_awareness()
  store_supports_native_locking()
  is_using_persist_cache()
  use_static_acceleration()
  is_in_persist_cache()
  static_acceleration_has()
  get_from_persist_cache()
  static_acceleration_get()
  set_in_persist_cache()
  static_acceleration_set()
  delete_from_persist_cache()
  static_acceleration_delete()
  static_acceleration_purge()
  now()
  get_purge_token()
  compare_purge_tokens()
  purge_current_user()

cache_application:: (13 methods):
  __construct()
  get_identifier()
  __clone()
  acquire_lock()
  check_lock_state()
  release_lock()
  ensure_cachelock_available()
  set()
  set_many()
  get()
  get_many()
  delete()
  delete_many()

cache_session:: (17 methods):
  __construct()
  set_session_id()
  get_key_prefix()
  parse_key()
  check_tracked_user()
  purge_current_user()
  get()
  set()
  delete()
  get_many()
  delete_many()
  set_many()
  purge()
  has()
  has_all()
  has_any()
  use_static_acceleration()

cache_request:: (0 methods):


Class: cache  - X-Ref

The main cache class.

This class if the first class that any end developer will interact with.
In order to create an instance of a cache that they can work with they must call one of the static make methods belonging
to this class.

make($component, $area, array $identifiers = array()   X-Ref
Creates a new cache instance for a pre-defined definition.

param: string $component The component for the definition
param: string $area The area for the definition
param: array $identifiers Any additional identifiers that should be provided to the definition.
param: string $unused Used to be datasourceaggregate but that was removed and this is now unused.
return: cache_application|cache_session|cache_store

make_from_params($mode, $component, $area, array $identifiers = array()   X-Ref
Creates a new cache instance based upon the given params.

param: int $mode One of cache_store::MODE_*
param: string $component The component this cache relates to.
param: string $area The area this cache relates to.
param: array $identifiers Any additional identifiers that should be provided to the definition.
param: array $options An array of options, available options are:
return: cache_application|cache_session|cache_store

__construct(cache_definition $definition, cache_store $store, $loader = null)   X-Ref
Constructs a new cache instance.

You should not call this method from your code, instead you should use the cache::make methods.

This method is public so that the cache_factory is able to instantiate cache instances.
Ideally we would make this method protected and expose its construction to the factory method internally somehow.
The factory class is responsible for this in order to centralise the storage of instances once created. This way if needed
we can force a reset of the cache API (used during unit testing).

param: cache_definition $definition The definition for the cache instance.
param: cache_store $store The store that cache should use.
param: cache_loader|cache_data_source $loader The next loader in the chain or the data source if there is one and there

set_loader(cache_loader $loader)   X-Ref
Set the loader for this cache.

param: cache_loader $loader

set_data_source(cache_data_source $datasource)   X-Ref
Set the data source for this cache.

param: cache_data_source $datasource

set_is_sub_loader($setting = true)   X-Ref
Used to inform the loader of its state as a sub loader, or as the top of the chain.

This is important as it ensures that we do not have more than one loader keeping static acceleration data.
Subloaders need to be "pure" loaders in the sense that they are used to store and retrieve information from stores or the
next loader/data source in the chain.
Nothing fancy, nothing flash.

param: bool $setting

set_identifiers(array $identifiers)   X-Ref
Alters the identifiers that have been provided to the definition.

This is an advanced method and should not be used unless really needed.
It allows the developer to slightly alter the definition without having to re-establish the cache.
It will cause more processing as the definition will need to clear and reprepare some of its properties.

param: array $identifiers

handle_invalidation_events()   X-Ref
Process any outstanding invalidation events for the cache we are registering,

Identifiers and event invalidation are not compatible with each other at this time.
As a result the cache does not need to consider identifiers when working out what to invalidate.

get($key, $strictness = IGNORE_MISSING)   X-Ref
Retrieves the value for the given key from the cache.

param: string|int $key The key for the data being requested.
param: int $strictness One of IGNORE_MISSING | MUST_EXIST
return: mixed|false The data from the cache or false if the key did not exist within the cache.

get_many(array $keys, $strictness = IGNORE_MISSING)   X-Ref
Retrieves an array of values for an array of keys.

Using this function comes with potential performance implications.
Not all cache stores will support get_many/set_many operations and in order to replicate this functionality will call
the equivalent singular method for each item provided.
This should not deter you from using this function as there is a performance benefit in situations where the cache store
does support it, but you should be aware of this fact.

param: array $keys The keys of the data being requested.
param: int $strictness One of IGNORE_MISSING or MUST_EXIST.
return: array An array of key value pairs for the items that could be retrieved from the cache.

set($key, $data)   X-Ref
Sends a key => value pair to the cache.

<code>
// This code will add four entries to the cache, one for each url.
$cache->set('main', 'http://moodle.org');
$cache->set('docs', 'http://docs.moodle.org');
$cache->set('tracker', 'http://tracker.moodle.org');
$cache->set('qa', 'http://qa.moodle.net');
</code>

param: string|int $key The key for the data being requested.
param: mixed $data The data to set against the key.
return: bool True on success, false otherwise.

unref($data)   X-Ref
Removes references where required.

param: stdClass|array $data
return: mixed What ever was put in but without any references.

requires_serialisation($value, $depth = 1)   X-Ref
Checks to see if a var requires serialisation.

param: mixed $value The value to check.
param: int $depth Used to ensure we don't enter an endless loop (think recursion).
return: bool Returns true if the value is going to require serialisation in order to ensure a reference free copy

deep_clone($value)   X-Ref
Creates a reference free clone of the given value.

param: mixed $value
return: mixed

set_many(array $keyvaluearray)   X-Ref
Sends several key => value pairs to the cache.

Using this function comes with potential performance implications.
Not all cache stores will support get_many/set_many operations and in order to replicate this functionality will call
the equivalent singular method for each item provided.
This should not deter you from using this function as there is a performance benefit in situations where the cache store
does support it, but you should be aware of this fact.

<code>
// This code will add four entries to the cache, one for each url.
$cache->set_many(array(
'main' => 'http://moodle.org',
'docs' => 'http://docs.moodle.org',
'tracker' => 'http://tracker.moodle.org',
'qa' => ''http://qa.moodle.net'
));
</code>

param: array $keyvaluearray An array of key => value pairs to send to the cache.
return: int The number of items successfully set. It is up to the developer to check this matches the number of items.

has($key, $tryloadifpossible = false)   X-Ref
Test is a cache has a key.

The use of the has methods is strongly discouraged. In a high load environment the cache may well change between the
test and any subsequent action (get, set, delete etc).
Instead it is recommended to write your code in such a way they it performs the following steps:
<ol>
<li>Attempt to retrieve the information.</li>
<li>Generate the information.</li>
<li>Attempt to set the information</li>
</ol>

Its also worth mentioning that not all stores support key tests.
For stores that don't support key tests this functionality is mimicked by using the equivalent get method.
Just one more reason you should not use these methods unless you have a very good reason to do so.

param: string|int $key
param: bool $tryloadifpossible If set to true, the cache doesn't contain the key, and there is another cache loader or
return: bool True if the cache has the requested key, false otherwise.

has_all(array $keys)   X-Ref
Test is a cache has all of the given keys.

It is strongly recommended to avoid the use of this function if not absolutely required.
In a high load environment the cache may well change between the test and any subsequent action (get, set, delete etc).

Its also worth mentioning that not all stores support key tests.
For stores that don't support key tests this functionality is mimicked by using the equivalent get method.
Just one more reason you should not use these methods unless you have a very good reason to do so.

param: array $keys
return: bool True if the cache has all of the given keys, false otherwise.

has_any(array $keys)   X-Ref
Test if a cache has at least one of the given keys.

It is strongly recommended to avoid the use of this function if not absolutely required.
In a high load environment the cache may well change between the test and any subsequent action (get, set, delete etc).

Its also worth mentioning that not all stores support key tests.
For stores that don't support key tests this functionality is mimicked by using the equivalent get method.
Just one more reason you should not use these methods unless you have a very good reason to do so.

param: array $keys
return: bool True if the cache has at least one of the given keys

delete($key, $recurse = true)   X-Ref
Delete the given key from the cache.

param: string|int $key The key to delete.
param: bool $recurse When set to true the key will also be deleted from all stacked cache loaders and their stores.
return: bool True of success, false otherwise.

delete_many(array $keys, $recurse = true)   X-Ref
Delete all of the given keys from the cache.

param: array $keys The key to delete.
param: bool $recurse When set to true the key will also be deleted from all stacked cache loaders and their stores.
return: int The number of items successfully deleted.

purge()   X-Ref
Purges the cache store, and loader if there is one.

return: bool True on success, false otherwise

parse_key($key)   X-Ref
Parses the key turning it into a string (or array is required) suitable to be passed to the cache store.

param: string|int $key As passed to get|set|delete etc.
return: string|array String unless the store supports multi-identifiers in which case an array if returned.

has_a_ttl()   X-Ref
Returns true if the cache is making use of a ttl.

return: bool

store_supports_native_ttl()   X-Ref
Returns true if the cache store supports native ttl.

return: bool

get_definition()   X-Ref
Returns the cache definition.

return: cache_definition

get_store()   X-Ref
Returns the cache store

return: cache_store

get_loader()   X-Ref
Returns the loader associated with this instance.

return: cache|false

get_datasource()   X-Ref
Returns the data source associated with this cache.

return: cache_data_source|false

store_supports_key_awareness()   X-Ref
Returns true if the store supports key awareness.

return: bool

store_supports_native_locking()   X-Ref
Returns true if the store natively supports locking.

return: bool

is_using_persist_cache()   X-Ref


use_static_acceleration()   X-Ref
Returns true if this cache is making use of the static acceleration array.

return: bool

is_in_persist_cache()   X-Ref


static_acceleration_has($key)   X-Ref
Returns true if the requested key exists within the static acceleration array.

param: string $key The parsed key
return: bool

get_from_persist_cache()   X-Ref


static_acceleration_get($key)   X-Ref
Returns the item from the static acceleration array if it exists there.

param: string $key The parsed key
return: mixed|false Dereferenced data from the static acceleration array or false if it wasn't there.

set_in_persist_cache()   X-Ref


static_acceleration_set($key, $data)   X-Ref
Sets a key value pair into the static acceleration array.

param: string $key The parsed key
param: mixed $data
return: bool

delete_from_persist_cache()   X-Ref


static_acceleration_delete($key)   X-Ref
Deletes an item from the static acceleration array.

param: string|int $key As given to get|set|delete
return: bool True on success, false otherwise.

static_acceleration_purge()   X-Ref
Purge the static acceleration cache.


now($float = false)   X-Ref
Returns the timestamp from the first request for the time from the cache API.

This stamp needs to be used for all ttl and time based operations to ensure that we don't end up with
timing issues.

param: bool    $float Whether to use floating precision accuracy.
return: int|float

get_purge_token($reset = false)   X-Ref
Get a 'purge' token used for cache invalidation handling.

Note: This function is intended for use from within the Cache API only and not by plugins, or cache stores.

param: bool    $reset  Whether to reset the token and generate a new one.
return: string

compare_purge_tokens($tokena, $tokenb)   X-Ref
Compare a pair of purge tokens.

If the two tokens are identical, then the return value is 0.
If the time component of token A is newer than token B, then a positive value is returned.
If the time component of token B is newer than token A, then a negative value is returned.

Note: This function is intended for use from within the Cache API only and not by plugins, or cache stores.

param: string  $tokena
param: string  $tokenb
return: int

purge_current_user()   X-Ref
Subclasses may support purging cache of all data belonging to the
current user.


Class: cache_application  - X-Ref

An application cache.

This class is used for application caches returned by the cache::make methods.
On top of the standard functionality it also allows locking to be required and or manually operated.

This cache class should never be interacted with directly. Instead you should always use the cache::make methods.
It is technically possible to call those methods through this class however there is no guarantee that you will get an
instance of this class back again.

__construct(cache_definition $definition, cache_store $store, $loader = null)   X-Ref
Overrides the cache construct method.

You should not call this method from your code, instead you should use the cache::make methods.

param: cache_definition $definition
param: cache_store $store
param: cache_loader|cache_data_source $loader

get_identifier()   X-Ref
Returns the identifier to use

return: string

__clone()   X-Ref
Fixes the instance up after a clone.


acquire_lock($key)   X-Ref
Acquires a lock on the given key.

This is done automatically if the definition requires it.
It is recommended to use a definition if you want to have locking although it is possible to do locking without having
it required by the definition.
The problem with such an approach is that you cannot ensure that code will consistently use locking. You will need to
rely on the integrators review skills.

param: string|int $key The key as given to get|set|delete
return: bool Returns true if the lock could be acquired, false otherwise.

check_lock_state($key)   X-Ref
Checks if this cache has a lock on the given key.

param: string|int $key The key as given to get|set|delete
return: bool|null Returns true if there is a lock and this cache has it, null if no one has a lock on that key, false if

release_lock($key)   X-Ref
Releases the lock this cache has on the given key

param: string|int $key
return: bool True if the operation succeeded, false otherwise.

ensure_cachelock_available()   X-Ref
Ensure that the dedicated lock store is ready to go.

This should only happen if the cache store doesn't natively support it.

set($key, $data)   X-Ref
Sends a key => value pair to the cache.

<code>
// This code will add four entries to the cache, one for each url.
$cache->set('main', 'http://moodle.org');
$cache->set('docs', 'http://docs.moodle.org');
$cache->set('tracker', 'http://tracker.moodle.org');
$cache->set('qa', 'http://qa.moodle.net');
</code>

param: string|int $key The key for the data being requested.
param: mixed $data The data to set against the key.
return: bool True on success, false otherwise.

set_many(array $keyvaluearray)   X-Ref
Sends several key => value pairs to the cache.

Using this function comes with potential performance implications.
Not all cache stores will support get_many/set_many operations and in order to replicate this functionality will call
the equivalent singular method for each item provided.
This should not deter you from using this function as there is a performance benefit in situations where the cache store
does support it, but you should be aware of this fact.

<code>
// This code will add four entries to the cache, one for each url.
$cache->set_many(array(
'main' => 'http://moodle.org',
'docs' => 'http://docs.moodle.org',
'tracker' => 'http://tracker.moodle.org',
'qa' => ''http://qa.moodle.net'
));
</code>

param: array $keyvaluearray An array of key => value pairs to send to the cache.
return: int The number of items successfully set. It is up to the developer to check this matches the number of items.

get($key, $strictness = IGNORE_MISSING)   X-Ref
Retrieves the value for the given key from the cache.

param: string|int $key The key for the data being requested.
param: int $strictness One of IGNORE_MISSING | MUST_EXIST
return: mixed|false The data from the cache or false if the key did not exist within the cache.

get_many(array $keys, $strictness = IGNORE_MISSING)   X-Ref
Retrieves an array of values for an array of keys.

Using this function comes with potential performance implications.
Not all cache stores will support get_many/set_many operations and in order to replicate this functionality will call
the equivalent singular method for each item provided.
This should not deter you from using this function as there is a performance benefit in situations where the cache store
does support it, but you should be aware of this fact.

param: array $keys The keys of the data being requested.
param: int $strictness One of IGNORE_MISSING or MUST_EXIST.
return: array An array of key value pairs for the items that could be retrieved from the cache.

delete($key, $recurse = true)   X-Ref
Delete the given key from the cache.

param: string|int $key The key to delete.
param: bool $recurse When set to true the key will also be deleted from all stacked cache loaders and their stores.
return: bool True of success, false otherwise.

delete_many(array $keys, $recurse = true)   X-Ref
Delete all of the given keys from the cache.

param: array $keys The key to delete.
param: bool $recurse When set to true the key will also be deleted from all stacked cache loaders and their stores.
return: int The number of items successfully deleted.

Class: cache_session  - X-Ref

A session cache.

This class is used for session caches returned by the cache::make methods.

It differs from the application loader in a couple of noteable ways:
1. Sessions are always expected to exist.
Because of this we don't ever use the static acceleration array.
2. Session data for a loader instance (store + definition) is consolidate into a
single array for storage within the store.
Along with this we embed a lastaccessed time with the data. This way we can
check sessions for a last access time.
3. Session stores are required to support key searching and must
implement cache_is_searchable. This ensures stores used for the cache can be
targetted for garbage collection of session data.

This cache class should never be interacted with directly. Instead you should always use the cache::make methods.
It is technically possible to call those methods through this class however there is no guarantee that you will get an
instance of this class back again.

__construct(cache_definition $definition, cache_store $store, $loader = null)   X-Ref
Override the cache::construct method.

This function gets overriden so that we can process any invalidation events if need be.
If the definition doesn't have any invalidation events then this occurs exactly as it would for the cache class.
Otherwise we look at the last invalidation time and then check the invalidation data for events that have occured
between then now.

You should not call this method from your code, instead you should use the cache::make methods.

param: cache_definition $definition
param: cache_store $store
param: cache_loader|cache_data_source $loader

set_session_id()   X-Ref
Sets the session id for the loader.


get_key_prefix()   X-Ref
Returns the prefix used for all keys.

return: string

parse_key($key)   X-Ref
Parses the key turning it into a string (or array is required) suitable to be passed to the cache store.

This function is called for every operation that uses keys. For this reason we use this function to also check
that the current user is the same as the user who last used this cache.

On top of that if prepends the string 'sess_' to the start of all keys. The _ ensures things are easily identifiable.

param: string|int $key As passed to get|set|delete etc.
return: string|array String unless the store supports multi-identifiers in which case an array if returned.

check_tracked_user()   X-Ref
Check that this cache instance is tracking the current user.


purge_current_user()   X-Ref
Purges the session cache of all data belonging to the current user.


get($key, $strictness = IGNORE_MISSING)   X-Ref
Retrieves the value for the given key from the cache.

param: string|int $key The key for the data being requested.
param: int $strictness One of IGNORE_MISSING | MUST_EXIST
return: mixed|false The data from the cache or false if the key did not exist within the cache.

set($key, $data)   X-Ref
Sends a key => value pair to the cache.

<code>
// This code will add four entries to the cache, one for each url.
$cache->set('main', 'http://moodle.org');
$cache->set('docs', 'http://docs.moodle.org');
$cache->set('tracker', 'http://tracker.moodle.org');
$cache->set('qa', 'http://qa.moodle.net');
</code>

param: string|int $key The key for the data being requested.
param: mixed $data The data to set against the key.
return: bool True on success, false otherwise.

delete($key, $recurse = true)   X-Ref
Delete the given key from the cache.

param: string|int $key The key to delete.
param: bool $recurse When set to true the key will also be deleted from all stacked cache loaders and their stores.
return: bool True of success, false otherwise.

get_many(array $keys, $strictness = IGNORE_MISSING)   X-Ref
Retrieves an array of values for an array of keys.

Using this function comes with potential performance implications.
Not all cache stores will support get_many/set_many operations and in order to replicate this functionality will call
the equivalent singular method for each item provided.
This should not deter you from using this function as there is a performance benefit in situations where the cache store
does support it, but you should be aware of this fact.

param: array $keys The keys of the data being requested.
param: int $strictness One of IGNORE_MISSING or MUST_EXIST.
return: array An array of key value pairs for the items that could be retrieved from the cache.

delete_many(array $keys, $recurse = true)   X-Ref
Delete all of the given keys from the cache.

param: array $keys The key to delete.
param: bool $recurse When set to true the key will also be deleted from all stacked cache loaders and their stores.
return: int The number of items successfully deleted.

set_many(array $keyvaluearray)   X-Ref
Sends several key => value pairs to the cache.

Using this function comes with potential performance implications.
Not all cache stores will support get_many/set_many operations and in order to replicate this functionality will call
the equivalent singular method for each item provided.
This should not deter you from using this function as there is a performance benefit in situations where the cache store
does support it, but you should be aware of this fact.

<code>
// This code will add four entries to the cache, one for each url.
$cache->set_many(array(
'main' => 'http://moodle.org',
'docs' => 'http://docs.moodle.org',
'tracker' => 'http://tracker.moodle.org',
'qa' => ''http://qa.moodle.net'
));
</code>

param: array $keyvaluearray An array of key => value pairs to send to the cache.
return: int The number of items successfully set. It is up to the developer to check this matches the number of items.

purge()   X-Ref
Purges the cache store, and loader if there is one.

return: bool True on success, false otherwise

has($key, $tryloadifpossible = false)   X-Ref
Test is a cache has a key.

The use of the has methods is strongly discouraged. In a high load environment the cache may well change between the
test and any subsequent action (get, set, delete etc).
Instead it is recommended to write your code in such a way they it performs the following steps:
<ol>
<li>Attempt to retrieve the information.</li>
<li>Generate the information.</li>
<li>Attempt to set the information</li>
</ol>

Its also worth mentioning that not all stores support key tests.
For stores that don't support key tests this functionality is mimicked by using the equivalent get method.
Just one more reason you should not use these methods unless you have a very good reason to do so.

param: string|int $key
param: bool $tryloadifpossible If set to true, the cache doesn't contain the key, and there is another cache loader or
return: bool True if the cache has the requested key, false otherwise.

has_all(array $keys)   X-Ref
Test is a cache has all of the given keys.

It is strongly recommended to avoid the use of this function if not absolutely required.
In a high load environment the cache may well change between the test and any subsequent action (get, set, delete etc).

Its also worth mentioning that not all stores support key tests.
For stores that don't support key tests this functionality is mimicked by using the equivalent get method.
Just one more reason you should not use these methods unless you have a very good reason to do so.

param: array $keys
return: bool True if the cache has all of the given keys, false otherwise.

has_any(array $keys)   X-Ref
Test if a cache has at least one of the given keys.

It is strongly recommended to avoid the use of this function if not absolutely required.
In a high load environment the cache may well change between the test and any subsequent action (get, set, delete etc).

Its also worth mentioning that not all stores support key tests.
For stores that don't support key tests this functionality is mimicked by using the equivalent get method.
Just one more reason you should not use these methods unless you have a very good reason to do so.

param: array $keys
return: bool True if the cache has at least one of the given keys

use_static_acceleration()   X-Ref
The session loader never uses static acceleration.
Instead it stores things in the static $session variable. Shared between all session loaders.

return: bool

Class: cache_request  - X-Ref

An request cache.

This class is used for request caches returned by the cache::make methods.

This cache class should never be interacted with directly. Instead you should always use the cache::make methods.
It is technically possible to call those methods through this class however there is no guarantee that you will get an
instance of this class back again.