Search moodle.org's
Developer Documentation

See Release Notes

  • Bug fixes for general core bugs in 4.3.x will end 7 October 2024 (12 months).
  • Bug fixes for security issues in 4.3.x will end 21 April 2025 (18 months).
  • PHP version: minimum PHP 8.0.0 Note: minimum PHP version has increased since Moodle 4.1. PHP 8.2.x is supported too.

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

   1  <?php
   2  // This file is part of Moodle - http://moodle.org/
   3  //
   4  // Moodle is free software: you can redistribute it and/or modify
   5  // it under the terms of the GNU General Public License as published by
   6  // the Free Software Foundation, either version 3 of the License, or
   7  // (at your option) any later version.
   8  //
   9  // Moodle is distributed in the hope that it will be useful,
  10  // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  12  // GNU General Public License for more details.
  13  //
  14  // You should have received a copy of the GNU General Public License
  15  // along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
  16  
  17  /**
  18   * Cache API interfaces
  19   *
  20   * This file is part of Moodle's cache API, affectionately called MUC.
  21   * It contains the components that are requried in order to use caching.
  22   *
  23   * @package    core
  24   * @category   cache
  25   * @copyright  2012 Sam Hemelryk
  26   * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  27   */
  28  
  29  defined('MOODLE_INTERNAL') || die();
  30  
  31  /**
  32   * Cache Loader.
  33   *
  34   * This cache loader interface provides the required structure for classes that wish to be interacted with as a
  35   * means of accessing and interacting with a cache.
  36   *
  37   * Can be implemented by any class wishing to be a cache loader.
  38   */
  39  interface cache_loader {
  40  
  41      /**
  42       * Retrieves the value for the given key from the cache.
  43       *
  44       * @param string|int $key The key for the data being requested.
  45       * @param int $strictness One of IGNORE_MISSING or MUST_EXIST.
  46       * @return mixed The data retrieved from the cache, or false if the key did not exist within the cache.
  47       *      If MUST_EXIST was used then an exception will be thrown if the key does not exist within the cache.
  48       */
  49      public function get($key, $strictness = IGNORE_MISSING);
  50  
  51      /**
  52       * Retrieves the value and actual version for the given key, with at least the required version.
  53       *
  54       * If there is no value for the key, or there is a value but it doesn't have the required
  55       * version, then this function will return false (or throw an exception if you set strictness
  56       * to MUST_EXIST).
  57       *
  58       * This function can be used to make it easier to support localisable caches (where the cache
  59       * could be stored on a local server as well as a shared cache). Specifying the version means
  60       * that it will automatically retrieve the correct version if available, either from the local
  61       * server or [if that has an older version] from the shared server.
  62       *
  63       * If the cached version is newer than specified version, it will be returned regardless. For
  64       * example, if you request version 4, but the locally cached version is 5, it will be returned.
  65       * If you request version 6, and the locally cached version is 5, then the system will look in
  66       * higher-level caches (if any); if there still isn't a version 6 or greater, it will return
  67       * null.
  68       *
  69       * You must use this function if you use set_versioned.
  70       *
  71       * @param string|int $key The key for the data being requested.
  72       * @param int $requiredversion Minimum required version of the data
  73       * @param int $strictness One of IGNORE_MISSING or MUST_EXIST.
  74       * @param mixed $actualversion If specified, will be set to the actual version number retrieved
  75       * @return mixed Data from the cache, or false if the key did not exist or was too old
  76       */
  77      public function get_versioned($key, int $requiredversion, int $strictness = IGNORE_MISSING, &$actualversion = null);
  78  
  79      /**
  80       * Retrieves an array of values for an array of keys.
  81       *
  82       * Using this function comes with potential performance implications.
  83       * Not all cache stores will support get_many/set_many operations and in order to replicate this functionality will call
  84       * the equivalent singular method for each item provided.
  85       * This should not deter you from using this function as there is a performance benefit in situations where the cache
  86       * store does support it, but you should be aware of this fact.
  87       *
  88       * @param array $keys The keys of the data being requested.
  89       * @param int $strictness One of IGNORE_MISSING or MUST_EXIST.
  90       * @return array An array of key value pairs for the items that could be retrieved from the cache.
  91       *      If MUST_EXIST was used and not all keys existed within the cache then an exception will be thrown.
  92       *      Otherwise any key that did not exist will have a data value of false within the results.
  93       */
  94      public function get_many(array $keys, $strictness = IGNORE_MISSING);
  95  
  96      /**
  97       * Sends a key => value pair to the cache.
  98       *
  99       * <code>
 100       * // This code will add four entries to the cache, one for each url.
 101       * $cache->set('main', 'http://moodle.org');
 102       * $cache->set('docs', 'http://docs.moodle.org');
 103       * $cache->set('tracker', 'http://tracker.moodle.org');
 104       * $cache->set('qa', 'http://qa.moodle.net');
 105       * </code>
 106       *
 107       * @param string|int $key The key for the data being requested.
 108       * @param mixed $data The data to set against the key.
 109       * @return bool True on success, false otherwise.
 110       */
 111      public function set($key, $data);
 112  
 113      /**
 114       * Sets the value for the given key with the given version.
 115       *
 116       * The cache does not store multiple versions - any existing version will be overwritten with
 117       * this one. This function should only be used if there is a known 'current version' (e.g.
 118       * stored in a database table). It only ensures that the cache does not return outdated data.
 119       *
 120       * This function can be used to help implement localisable caches (where the cache could be
 121       * stored on a local server as well as a shared cache). The version will be recorded alongside
 122       * the item and get_versioned will always return the correct version.
 123       *
 124       * The version number must be an integer that always increases. This could be based on the
 125       * current time, or a stored value that increases by 1 each time it changes, etc.
 126       *
 127       * If you use this function you must use get_versioned to retrieve the data.
 128       *
 129       * @param string|int $key The key for the data being set.
 130       * @param int $version Integer for the version of the data
 131       * @param mixed $data The data to set against the key.
 132       * @return bool True on success, false otherwise.
 133       */
 134      public function set_versioned($key, int $version, $data): bool;
 135  
 136      /**
 137       * Sends several key => value pairs to the cache.
 138       *
 139       * Using this function comes with potential performance implications.
 140       * Not all cache stores will support get_many/set_many operations and in order to replicate this functionality will call
 141       * the equivalent singular method for each item provided.
 142       * This should not deter you from using this function as there is a performance benefit in situations where the cache store
 143       * does support it, but you should be aware of this fact.
 144       *
 145       * <code>
 146       * // This code will add four entries to the cache, one for each url.
 147       * $cache->set_many(array(
 148       *     'main' => 'http://moodle.org',
 149       *     'docs' => 'http://docs.moodle.org',
 150       *     'tracker' => 'http://tracker.moodle.org',
 151       *     'qa' => ''http://qa.moodle.net'
 152       * ));
 153       * </code>
 154       *
 155       * @param array $keyvaluearray An array of key => value pairs to send to the cache.
 156       * @return int The number of items successfully set. It is up to the developer to check this matches the number of items.
 157       *      ... if they care that is.
 158       */
 159      public function set_many(array $keyvaluearray);
 160  
 161      /**
 162       * Test is a cache has a key.
 163       *
 164       * The use of the has methods is strongly discouraged. In a high load environment the cache may well change between the
 165       * test and any subsequent action (get, set, delete etc).
 166       * Instead it is recommended to write your code in such a way they it performs the following steps:
 167       * <ol>
 168       * <li>Attempt to retrieve the information.</li>
 169       * <li>Generate the information.</li>
 170       * <li>Attempt to set the information</li>
 171       * </ol>
 172       *
 173       * Its also worth mentioning that not all stores support key tests.
 174       * For stores that don't support key tests this functionality is mimicked by using the equivalent get method.
 175       * Just one more reason you should not use these methods unless you have a very good reason to do so.
 176       *
 177       * @param string|int $key
 178       * @return bool True if the cache has the requested key, false otherwise.
 179       */
 180      public function has($key);
 181  
 182      /**
 183       * Test if a cache has at least one of the given keys.
 184       *
 185       * It is strongly recommended to avoid the use of this function if not absolutely required.
 186       * In a high load environment the cache may well change between the test and any subsequent action (get, set, delete etc).
 187       *
 188       * Its also worth mentioning that not all stores support key tests.
 189       * For stores that don't support key tests this functionality is mimicked by using the equivalent get method.
 190       * Just one more reason you should not use these methods unless you have a very good reason to do so.
 191       *
 192       * @param array $keys
 193       * @return bool True if the cache has at least one of the given keys
 194       */
 195      public function has_any(array $keys);
 196  
 197      /**
 198       * Test is a cache has all of the given keys.
 199       *
 200       * It is strongly recommended to avoid the use of this function if not absolutely required.
 201       * In a high load environment the cache may well change between the test and any subsequent action (get, set, delete etc).
 202       *
 203       * Its also worth mentioning that not all stores support key tests.
 204       * For stores that don't support key tests this functionality is mimicked by using the equivalent get method.
 205       * Just one more reason you should not use these methods unless you have a very good reason to do so.
 206       *
 207       * @param array $keys
 208       * @return bool True if the cache has all of the given keys, false otherwise.
 209       */
 210      public function has_all(array $keys);
 211  
 212      /**
 213       * Delete the given key from the cache.
 214       *
 215       * @param string|int $key The key to delete.
 216       * @param bool $recurse When set to true the key will also be deleted from all stacked cache loaders and their stores.
 217       *     This happens by default and ensure that all the caches are consistent. It is NOT recommended to change this.
 218       * @return bool True of success, false otherwise.
 219       */
 220      public function delete($key, $recurse = true);
 221  
 222      /**
 223       * Delete all of the given keys from the cache.
 224       *
 225       * @param array $keys The key to delete.
 226       * @param bool $recurse When set to true the key will also be deleted from all stacked cache loaders and their stores.
 227       *     This happens by default and ensure that all the caches are consistent. It is NOT recommended to change this.
 228       * @return int The number of items successfully deleted.
 229       */
 230      public function delete_many(array $keys, $recurse = true);
 231  }
 232  
 233  /**
 234   * Cache Loader supporting locking.
 235   *
 236   * This interface should be given to classes already implementing cache_loader that also wish to support locking.
 237   * It outlines the required structure for utilising locking functionality when using a cache.
 238   *
 239   * Can be implemented by any class already implementing the cache_loader interface.
 240   */
 241  interface cache_loader_with_locking {
 242  
 243      /**
 244       * Acquires a lock for the given key.
 245       *
 246       * Please note that this happens automatically if the cache definition requires locking.
 247       * it is still made a public method so that adhoc caches can use it if they choose.
 248       * However this doesn't guarantee consistent access. It will become the responsibility of the calling code to ensure
 249       * locks are acquired, checked, and released.
 250       *
 251       * Prior to Moodle 4,3 this function used to return false if the lock cannot be obtained. It
 252       * now always returns true, and throws an exception if the lock cannot be obtained.
 253       *
 254       * @param string|int $key
 255       * @return bool Always returns true (for backwards compatibility)
 256       * @throws moodle_exception If the lock cannot be obtained after a timeout
 257       */
 258      public function acquire_lock($key);
 259  
 260      /**
 261       * Checks if the cache loader owns the lock for the given key.
 262       *
 263       * Please note that this happens automatically if the cache definition requires locking.
 264       * it is still made a public method so that adhoc caches can use it if they choose.
 265       * However this doesn't guarantee consistent access. It will become the responsibility of the calling code to ensure
 266       * locks are acquired, checked, and released.
 267       *
 268       * @param string|int $key
 269       * @return bool True if this code has the lock, false if there is a lock but this code doesn't have it,
 270       *      null if there is no lock.
 271       */
 272      public function check_lock_state($key);
 273  
 274      /**
 275       * Releases the lock for the given key.
 276       *
 277       * Please note that this happens automatically if the cache definition requires locking.
 278       * it is still made a public method so that adhoc caches can use it if they choose.
 279       * However this doesn't guarantee consistent access. It will become the responsibility of the calling code to ensure
 280       * locks are acquired, checked, and released.
 281       *
 282       * @param string|int $key
 283       * @return bool True if the lock has been released, false if there was a problem releasing the lock.
 284       */
 285      public function release_lock($key);
 286  }
 287  
 288  /**
 289   * Cache store feature: locking
 290   *
 291   * This is a feature that cache stores can implement if they wish to support locking themselves rather
 292   * than having the cache loader handle it for them.
 293   *
 294   * Can be implemented by classes already implementing cache_store.
 295   */
 296  interface cache_is_lockable {
 297  
 298      /**
 299       * Acquires a lock on the given key for the given identifier.
 300       *
 301       * @param string $key The key we are locking.
 302       * @param string $ownerid The identifier so we can check if we have the lock or if it is someone else.
 303       *      The use of this property is entirely optional and implementations can act as they like upon it.
 304       * @return bool True if the lock could be acquired, false otherwise.
 305       */
 306      public function acquire_lock($key, $ownerid);
 307  
 308      /**
 309       * Test if there is already a lock for the given key and if there is whether it belongs to the calling code.
 310       *
 311       * @param string $key The key we are locking.
 312       * @param string $ownerid The identifier so we can check if we have the lock or if it is someone else.
 313       * @return bool True if this code has the lock, false if there is a lock but this code doesn't have it, null if there
 314       *      is no lock.
 315       */
 316      public function check_lock_state($key, $ownerid);
 317  
 318      /**
 319       * Releases the lock on the given key.
 320       *
 321       * @param string $key The key we are locking.
 322       * @param string $ownerid The identifier so we can check if we have the lock or if it is someone else.
 323       *      The use of this property is entirely optional and implementations can act as they like upon it.
 324       * @return bool True if the lock has been released, false if there was a problem releasing the lock.
 325       */
 326      public function release_lock($key, $ownerid);
 327  }
 328  
 329  /**
 330   * Cache store feature: key awareness.
 331   *
 332   * This is a feature that cache stores and cache loaders can both choose to implement.
 333   * If a cache store implements this then it will be made responsible for tests for items within the cache.
 334   * If the cache store being used doesn't implement this then it will be the responsibility of the cache loader to use the
 335   * equivalent get methods to mimick the functionality of these tests.
 336   *
 337   * Cache stores should only override these methods if they natively support such features or if they have a better performing
 338   * means of performing these tests than the handling that would otherwise take place in the cache_loader.
 339   *
 340   * Can be implemented by classes already implementing cache_store.
 341   */
 342  interface cache_is_key_aware {
 343  
 344      /**
 345       * Test is a cache has a key.
 346       *
 347       * The use of the has methods is strongly discouraged. In a high load environment the cache may well change between the
 348       * test and any subsequent action (get, set, delete etc).
 349       * Instead it is recommended to write your code in such a way they it performs the following steps:
 350       * <ol>
 351       * <li>Attempt to retrieve the information.</li>
 352       * <li>Generate the information.</li>
 353       * <li>Attempt to set the information</li>
 354       * </ol>
 355       *
 356       * Its also worth mentioning that not all stores support key tests.
 357       * For stores that don't support key tests this functionality is mimicked by using the equivalent get method.
 358       * Just one more reason you should not use these methods unless you have a very good reason to do so.
 359       *
 360       * @param string|int $key
 361       * @return bool True if the cache has the requested key, false otherwise.
 362       */
 363      public function has($key);
 364  
 365      /**
 366       * Test if a cache has at least one of the given keys.
 367       *
 368       * It is strongly recommended to avoid the use of this function if not absolutely required.
 369       * In a high load environment the cache may well change between the test and any subsequent action (get, set, delete etc).
 370       *
 371       * Its also worth mentioning that not all stores support key tests.
 372       * For stores that don't support key tests this functionality is mimicked by using the equivalent get method.
 373       * Just one more reason you should not use these methods unless you have a very good reason to do so.
 374       *
 375       * @param array $keys
 376       * @return bool True if the cache has at least one of the given keys
 377       */
 378      public function has_any(array $keys);
 379  
 380      /**
 381       * Test is a cache has all of the given keys.
 382       *
 383       * It is strongly recommended to avoid the use of this function if not absolutely required.
 384       * In a high load environment the cache may well change between the test and any subsequent action (get, set, delete etc).
 385       *
 386       * Its also worth mentioning that not all stores support key tests.
 387       * For stores that don't support key tests this functionality is mimicked by using the equivalent get method.
 388       * Just one more reason you should not use these methods unless you have a very good reason to do so.
 389       *
 390       * @param array $keys
 391       * @return bool True if the cache has all of the given keys, false otherwise.
 392       */
 393      public function has_all(array $keys);
 394  }
 395  
 396  /**
 397   * Cache store feature: keys are searchable.
 398   *
 399   * Cache stores can choose to implement this interface.
 400   * In order for a store to be usable as a session cache it must implement this interface.
 401   *
 402   * @since Moodle 2.4.4
 403   */
 404  interface cache_is_searchable {
 405      /**
 406       * Finds all of the keys being used by the cache store.
 407       *
 408       * @return array.
 409       */
 410      public function find_all();
 411  
 412      /**
 413       * Finds all of the keys whose keys start with the given prefix.
 414       *
 415       * @param string $prefix
 416       */
 417      public function find_by_prefix($prefix);
 418  }
 419  
 420  /**
 421   * Cache store feature: configurable.
 422   *
 423   * This feature should be implemented by all cache stores that are configurable when adding an instance.
 424   * It requires the implementation of methods required to convert form data into the a configuration array for the
 425   * store instance, and then the reverse converting configuration data into an array that can be used to set the
 426   * data for the edit form.
 427   *
 428   * Can be implemented by classes already implementing cache_store.
 429   */
 430  interface cache_is_configurable {
 431  
 432      /**
 433       * Given the data from the add instance form this function creates a configuration array.
 434       *
 435       * @param stdClass $data
 436       * @return array
 437       */
 438      public static function config_get_configuration_array($data);
 439  
 440      /**
 441       * Allows the cache store to set its data against the edit form before it is shown to the user.
 442       *
 443       * @param moodleform $editform
 444       * @param array $config
 445       */
 446      public static function config_set_edit_form_data(moodleform $editform, array $config);
 447  }
 448  
 449  /**
 450   * Cache Data Source.
 451   *
 452   * The cache data source interface can be implemented by any class within Moodle.
 453   * If implemented then the class can be reference in a cache definition and will be used to load information that cannot be
 454   * retrieved from the cache. As part of its retrieval that information will also be loaded into the cache.
 455   *
 456   * This allows developers to created a complete cache solution that can be used through code ensuring consistent cache
 457   * interaction and loading. Allowing them in turn to centralise code and help keeps things more easily maintainable.
 458   *
 459   * Can be implemented by any class.
 460   *
 461   * @package    core
 462   * @category   cache
 463   * @copyright  2012 Sam Hemelryk
 464   * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 465   */
 466  interface cache_data_source {
 467  
 468      /**
 469       * Returns an instance of the data source class that the cache can use for loading data using the other methods
 470       * specified by this interface.
 471       *
 472       * @param cache_definition $definition
 473       * @return object
 474       */
 475      public static function get_instance_for_cache(cache_definition $definition);
 476  
 477      /**
 478       * Loads the data for the key provided ready formatted for caching.
 479       *
 480       * @param string|int $key The key to load.
 481       * @return mixed What ever data should be returned, or false if it can't be loaded.
 482       */
 483      public function load_for_cache($key);
 484  
 485      /**
 486       * Loads several keys for the cache.
 487       *
 488       * @param array $keys An array of keys each of which will be string|int.
 489       * @return array An array of matching data items.
 490       */
 491      public function load_many_for_cache(array $keys);
 492  }
 493  
 494  /**
 495   * Versionable cache data source.
 496   *
 497   * This interface extends the main cache data source interface to add an extra required method if
 498   * the data source is to be used for a versioned cache.
 499   *
 500   * @package core_cache
 501   */
 502  interface cache_data_source_versionable extends cache_data_source {
 503      /**
 504       * Loads the data for the key provided ready formatted for caching.
 505       *
 506       * If there is no data for that key, or if the data for the required key has an older version
 507       * than the specified $requiredversion, then this returns null.
 508       *
 509       * If there is data then $actualversion should be set to the actual version number retrieved
 510       * (may be the same as $requiredversion or newer).
 511       *
 512       * @param string|int $key The key to load.
 513       * @param int $requiredversion Minimum required version
 514       * @param mixed $actualversion Should be set to the actual version number retrieved
 515       * @return mixed What ever data should be returned, or false if it can't be loaded.
 516       */
 517      public function load_for_cache_versioned($key, int $requiredversion, &$actualversion);
 518  }
 519  
 520  /**
 521   * Cacheable object.
 522   *
 523   * This interface can be implemented by any class that is going to be passed into a cache and allows it to take control of the
 524   * structure and the information about to be cached, as well as how to deal with it when it is retrieved from a cache.
 525   * Think of it like serialisation and the __sleep and __wakeup methods.
 526   * This is used because cache stores are responsible for how they interact with data and what they do when storing it. This
 527   * interface ensures there is always a guaranteed action.
 528   */
 529  interface cacheable_object {
 530  
 531      /**
 532       * Prepares the object for caching. Works like the __sleep method.
 533       *
 534       * @return mixed The data to cache, can be anything except a class that implements the cacheable_object... that would
 535       *      be dumb.
 536       */
 537      public function prepare_to_cache();
 538  
 539      /**
 540       * Takes the data provided by prepare_to_cache and reinitialises an instance of the associated from it.
 541       *
 542       * @param mixed $data
 543       * @return object The instance for the given data.
 544       */
 545      public static function wake_from_cache($data);
 546  }
 547  
 548  /**
 549   * Cache lock interface
 550   *
 551   * This interface needs to be inherited by all cache lock plugins.
 552   */
 553  interface cache_lock_interface {
 554      /**
 555       * Constructs an instance of the cache lock given its name and its configuration data
 556       *
 557       * @param string $name The unique name of the lock instance
 558       * @param array $configuration
 559       */
 560      public function __construct($name, array $configuration = array());
 561  
 562      /**
 563       * Acquires a lock on a given key.
 564       *
 565       * @param string $key The key to acquire a lock for.
 566       * @param string $ownerid An unique identifier for the owner of this lock. It is entirely optional for the cache lock plugin
 567       *      to use this. Each implementation can decide for themselves.
 568       * @param bool $block If set to true the application will wait until a lock can be acquired
 569       * @return bool True if the lock can be acquired false otherwise.
 570       */
 571      public function lock($key, $ownerid, $block = false);
 572  
 573      /**
 574       * Releases the lock held on a certain key.
 575       *
 576       * @param string $key The key to release the lock for.
 577       * @param string $ownerid An unique identifier for the owner of this lock. It is entirely optional for the cache lock plugin
 578       *      to use this. Each implementation can decide for themselves.
 579       * @param bool $forceunlock If set to true the lock will be removed if it exists regardless of whether or not we own it.
 580       */
 581      public function unlock($key, $ownerid, $forceunlock = false);
 582  
 583      /**
 584       * Checks the state of the given key.
 585       *
 586       * Returns true if the key is locked and belongs to the ownerid.
 587       * Returns false if the key is locked but does not belong to the ownerid.
 588       * Returns null if there is no lock
 589       *
 590       * @param string $key The key we are checking for.
 591       * @param string $ownerid The identifier so we can check if we have the lock or if it is someone else.
 592       * @return bool True if this code has the lock, false if there is a lock but this code doesn't have it, null if there
 593       *      is no lock.
 594       */
 595      public function check_state($key, $ownerid);
 596  
 597      /**
 598       * Cleans up any left over locks.
 599       *
 600       * This function MUST clean up any locks that have been acquired and not released during processing.
 601       * Although the situation of acquiring a lock and not releasing it should be insanely rare we need to deal with it.
 602       * Things such as unfortunate timeouts etc could cause this situation.
 603       */
 604      public function __destruct();
 605  }