2 // This file is part of Moodle - http://moodle.org/
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.
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.
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/>.
18 * This file contains the cache factory class.
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.
25 * @copyright 2012 Sam Hemelryk
26 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
29 defined('MOODLE_INTERNAL') || die();
32 * The cache factory class.
34 * This factory class is important because it stores instances of objects used by the cache API and returns them upon requests.
35 * This allows us to both reuse objects saving on overhead, and gives us an easy place to "reset" the cache API in situations that
36 * we need such as unit testing.
38 * @copyright 2012 Sam Hemelryk
39 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
43 /** The cache has not been initialised yet. */
44 const STATE_UNINITIALISED = 0;
45 /** The cache is in the process of initialising itself. */
46 const STATE_INITIALISING = 1;
47 /** The cache is in the process of saving its configuration file. */
48 const STATE_SAVING = 2;
49 /** The cache is ready to use. */
50 const STATE_READY = 3;
51 /** The cache is currently updating itself */
52 const STATE_UPDATING = 4;
53 /** The cache encountered an error while initialising. */
54 const STATE_ERROR_INITIALISING = 9;
55 /** The cache has been disabled. */
56 const STATE_DISABLED = 10;
57 /** The cache stores have been disabled */
58 const STATE_STORES_DISABLED = 11;
61 * An instance of the cache_factory class created upon the first request.
64 protected static $instance;
67 * An array containing caches created for definitions
70 protected $cachesfromdefinitions = array();
73 * Array of caches created by parameters, ad-hoc definitions will have been used.
76 protected $cachesfromparams = array();
79 * An array of stores organised by definitions.
82 protected $definitionstores = array();
85 * An array of instantiated stores.
88 protected $stores = array();
91 * An array of configuration instances
94 protected $configs = array();
97 * An array of initialised definitions
100 protected $definitions = array();
103 * An array of lock plugins.
106 protected $lockplugins = array();
109 * The current state of the cache API.
112 protected $state = 0;
115 * Returns an instance of the cache_factor method.
117 * @param bool $forcereload If set to true a new cache_factory instance will be created and used.
118 * @return cache_factory
120 public static function instance($forcereload = false) {
122 if ($forcereload || self::$instance === null) {
123 // Initialise a new factory to facilitate our needs.
124 if (defined('CACHE_DISABLE_ALL') && CACHE_DISABLE_ALL !== false) {
125 // The cache has been disabled. Load disabledlib and start using the factory designed to handle this
126 // situation. It will use disabled alternatives where available.
127 require_once($CFG->dirroot.'/cache/disabledlib.php');
128 self::$instance = new cache_factory_disabled();
130 // We're using the regular factory.
131 self::$instance = new cache_factory();
132 if (defined('CACHE_DISABLE_STORES') && CACHE_DISABLE_STORES !== false) {
133 // The cache stores have been disabled.
134 self::$instance->set_state(self::STATE_STORES_DISABLED);
138 return self::$instance;
142 * Protected constructor, please use the static instance method.
144 protected function __construct() {
145 // Nothing to do here.
149 * Resets the arrays containing instantiated caches, stores, and config instances.
151 public static function reset() {
152 $factory = self::instance();
153 $factory->reset_cache_instances();
154 $factory->configs = array();
155 $factory->definitions = array();
156 $factory->lockplugins = array(); // MUST be null in order to force its regeneration.
157 // Reset the state to uninitialised.
158 $factory->state = self::STATE_UNINITIALISED;
162 * Resets the stores, clearing the array of created stores.
164 * Cache objects still held onto by the code that initialised them will remain as is
165 * however all future requests for a cache/store will lead to a new instance being re-initialised.
167 public function reset_cache_instances() {
168 $this->cachesfromdefinitions = array();
169 $this->cachesfromparams = array();
170 $this->stores = array();
174 * Creates a cache object given the parameters for a definition.
176 * If a cache has already been created for the given definition then that cache instance will be returned.
178 * @param string $component
179 * @param string $area
180 * @param array $identifiers
181 * @param string $aggregate
182 * @return cache_application|cache_session|cache_request
184 public function create_cache_from_definition($component, $area, array $identifiers = array(), $aggregate = null) {
185 $definitionname = $component.'/'.$area;
186 if (isset($this->cachesfromdefinitions[$definitionname])) {
187 $cache = $this->cachesfromdefinitions[$definitionname];
188 $cache->set_identifiers($identifiers);
191 $definition = $this->create_definition($component, $area, $aggregate);
192 $definition->set_identifiers($identifiers);
193 $cache = $this->create_cache($definition, $identifiers);
194 // Loaders are always held onto to speed up subsequent requests.
195 $this->cachesfromdefinitions[$definitionname] = $cache;
200 * Creates an ad-hoc cache from the given param.
202 * If a cache has already been created using the same params then that cache instance will be returned.
205 * @param string $component
206 * @param string $area
207 * @param array $identifiers
208 * @param array $options An array of options, available options are:
209 * - simplekeys : Set to true if the keys you will use are a-zA-Z0-9_
210 * - simpledata : Set to true if the type of the data you are going to store is scalar, or an array of scalar vars
211 * - staticacceleration : If set to true the cache will hold onto data passing through it.
212 * - staticaccelerationsize : The maximum number of items to hold onto for acceleration purposes.
213 * @return cache_application|cache_session|cache_request
215 public function create_cache_from_params($mode, $component, $area, array $identifiers = array(), array $options = array()) {
216 $key = "{$mode}_{$component}_{$area}";
217 if (array_key_exists($key, $this->cachesfromparams)) {
218 return $this->cachesfromparams[$key];
220 $definition = cache_definition::load_adhoc($mode, $component, $area, $options);
221 $definition->set_identifiers($identifiers);
222 $cache = $this->create_cache($definition, $identifiers);
223 $this->cachesfromparams[$key] = $cache;
228 * Common public method to create a cache instance given a definition.
230 * This is used by the static make methods.
232 * @param cache_definition $definition
233 * @return cache_application|cache_session|cache_store
234 * @throws coding_exception
236 public function create_cache(cache_definition $definition) {
237 $class = $definition->get_cache_class();
238 $stores = cache_helper::get_stores_suitable_for_definition($definition);
239 foreach ($stores as $key => $store) {
240 if (!$store::are_requirements_met()) {
241 unset($stores[$key]);
244 if (count($stores) === 0) {
245 // Hmm still no stores, better provide a dummy store to mimic functionality. The dev will be none the wiser.
246 $stores[] = $this->create_dummy_store($definition);
249 if ($definition->has_data_source()) {
250 $loader = $definition->get_data_source();
252 while (($store = array_pop($stores)) !== null) {
253 $loader = new $class($definition, $store, $loader);
259 * Creates a store instance given its name and configuration.
261 * If the store has already been instantiated then the original object will be returned. (reused)
263 * @param string $name The name of the store (must be unique remember)
264 * @param array $details
265 * @param cache_definition $definition The definition to instantiate it for.
266 * @return boolean|cache_store
268 public function create_store_from_config($name, array $details, cache_definition $definition) {
269 if (!array_key_exists($name, $this->stores)) {
270 // Properties: name, plugin, configuration, class.
271 $class = $details['class'];
272 $store = new $class($details['name'], $details['configuration']);
273 $this->stores[$name] = $store;
275 /* @var cache_store $store */
276 $store = $this->stores[$name];
277 // We check are_requirements_met although we expect is_ready is going to check as well.
278 if (!$store::are_requirements_met() || !$store->is_ready() || !$store->is_supported_mode($definition->get_mode())) {
281 // We always create a clone of the original store.
282 // If we were to clone a store that had already been initialised with a definition then
283 // we'd run into a myriad of issues.
284 // We use a method of the store to create a clone rather than just creating it ourselves
285 // so that if any store out there doesn't handle cloning they can override this method in
286 // order to address the issues.
287 $store = $this->stores[$name]->create_clone($details);
288 $store->initialise($definition);
289 $definitionid = $definition->get_id();
290 if (!isset($this->definitionstores[$definitionid])) {
291 $this->definitionstores[$definitionid] = array();
293 $this->definitionstores[$definitionid][] = $store;
298 * Returns an array of cache stores that have been initialised for use in definitions.
299 * @param cache_definition $definition
302 public function get_store_instances_in_use(cache_definition $definition) {
303 $id = $definition->get_id();
304 if (!isset($this->definitionstores[$id])) {
307 return $this->definitionstores[$id];
311 * Returns the cache instances that have been used within this request.
315 public function get_caches_in_use() {
316 return $this->cachesfromdefinitions;
320 * Creates a cache config instance with the ability to write if required.
322 * @param bool $writer If set to true an instance that can update the configuration will be returned.
323 * @return cache_config|cache_config_writer
325 public function create_config_instance($writer = false) {
329 $class = 'cache_config';
330 // Check if this is a PHPUnit test and redirect to the phpunit config classes if it is.
331 if (defined('PHPUNIT_TEST') && PHPUNIT_TEST) {
332 require_once($CFG->dirroot.'/cache/locallib.php');
333 require_once($CFG->dirroot.'/cache/tests/fixtures/lib.php');
334 // We have just a single class for PHP unit tests. We don't care enough about its
335 // performance to do otherwise and having a single method allows us to inject things into it
337 $class = 'cache_config_phpunittest';
340 // Check if we need to create a config file with defaults.
341 $needtocreate = !$class::config_file_exists();
343 if ($writer || $needtocreate) {
344 require_once($CFG->dirroot.'/cache/locallib.php');
348 // Check if this is a PHPUnit test and redirect to the phpunit config classes if it is.
349 if (defined('PHPUNIT_TEST') && PHPUNIT_TEST) {
350 require_once($CFG->dirroot.'/cache/locallib.php');
351 require_once($CFG->dirroot.'/cache/tests/fixtures/lib.php');
352 // We have just a single class for PHP unit tests. We don't care enough about its
353 // performance to do otherwise and having a single method allows us to inject things into it
355 $class = 'cache_config_phpunittest';
360 // Create the default configuration.
361 // Update the state, we are now initialising the cache.
362 self::set_state(self::STATE_INITIALISING);
363 /** @var cache_config_writer $class */
364 $configuration = $class::create_default_configuration();
365 if ($configuration !== true) {
366 // Failed to create the default configuration. Disable the cache stores and update the state.
367 self::set_state(self::STATE_ERROR_INITIALISING);
368 $this->configs[$class] = new $class;
369 $this->configs[$class]->load($configuration);
374 if (!array_key_exists($class, $this->configs)) {
375 // Create a new instance and call it to load it.
376 $this->configs[$class] = new $class;
377 $this->configs[$class]->load();
381 // The cache is now ready to use. Update the state.
382 self::set_state(self::STATE_READY);
385 // Return the instance.
386 return $this->configs[$class];
390 * Creates a definition instance or returns the existing one if it has already been created.
391 * @param string $component
392 * @param string $area
393 * @param string $aggregate
394 * @return cache_definition
396 public function create_definition($component, $area, $aggregate = null) {
397 $id = $component.'/'.$area;
399 $id .= '::'.$aggregate;
401 if (!isset($this->definitions[$id])) {
402 // This is the first time this definition has been requested.
403 if ($this->is_initialising()) {
404 // We're initialising the cache right now. Don't try to create another config instance.
405 // We'll just use an ad-hoc cache for the time being.
406 $definition = cache_definition::load_adhoc(cache_store::MODE_REQUEST, $component, $area);
408 // Load all the known definitions and find the desired one.
409 $instance = $this->create_config_instance();
410 $definition = $instance->get_definition_by_id($id);
412 // Oh-oh the definition doesn't exist.
413 // There are several things that could be going on here.
414 // We may be installing/upgrading a site and have hit a definition that hasn't been used before.
415 // Of the developer may be trying to use a newly created definition.
416 if ($this->is_updating()) {
417 // The cache is presently initialising and the requested cache definition has not been found.
418 // This means that the cache initialisation has requested something from a cache (I had recursive nightmares about this).
419 // To serve this purpose and avoid errors we are going to make use of an ad-hoc cache rather than
420 // search for the definition which would possibly cause an infitite loop trying to initialise the cache.
421 $definition = cache_definition::load_adhoc(cache_store::MODE_REQUEST, $component, $area);
422 if ($aggregate !== null) {
423 // If you get here you deserve a warning. We have to use an ad-hoc cache here, so we can't find the definition and therefor
424 // can't find any information about the datasource or any of its aggregated.
426 debugging('An unknown cache was requested during development with an aggregate that could not be loaded. Ad-hoc cache used instead.', DEBUG_DEVELOPER);
430 // Either a typo of the developer has just created the definition and is using it for the first time.
432 $instance = $this->create_config_instance(true);
433 $instance->update_definitions();
434 $definition = $instance->get_definition_by_id($id);
436 throw new coding_exception('The requested cache definition does not exist.'. $id, $id);
437 } else if (!$this->is_disabled()) {
438 debugging('Cache definitions reparsed causing cache reset in order to locate definition.
439 You should bump the version number to ensure definitions are reprocessed.', DEBUG_DEVELOPER);
441 $definition = cache_definition::load($id, $definition, $aggregate);
444 $definition = cache_definition::load($id, $definition, $aggregate);
447 $this->definitions[$id] = $definition;
449 return $this->definitions[$id];
453 * Creates a dummy store object for use when a loader has no potential stores to use.
455 * @param cache_definition $definition
456 * @return cachestore_dummy
458 protected function create_dummy_store(cache_definition $definition) {
460 require_once($CFG->dirroot.'/cache/classes/dummystore.php');
461 $store = new cachestore_dummy();
462 $store->initialise($definition);
467 * Returns a lock instance ready for use.
469 * @param array $config
470 * @return cache_lock_interface
472 public function create_lock_instance(array $config) {
474 if (!array_key_exists('name', $config) || !array_key_exists('type', $config)) {
475 throw new coding_exception('Invalid cache lock instance provided');
477 $name = $config['name'];
478 $type = $config['type'];
479 unset($config['name']);
480 unset($config['type']);
482 if (!isset($this->lockplugins[$type])) {
483 $pluginname = substr($type, 10);
484 $file = $CFG->dirroot."/cache/locks/{$pluginname}/lib.php";
485 if (file_exists($file) && is_readable($file)) {
488 if (!class_exists($type)) {
489 throw new coding_exception('Invalid lock plugin requested.');
491 $this->lockplugins[$type] = $type;
493 if (!array_key_exists($type, $this->lockplugins)) {
494 throw new coding_exception('Invalid cache lock type.');
496 $class = $this->lockplugins[$type];
497 return new $class($name, $config);
501 * Returns the current state of the cache API.
505 public function get_state() {
510 * Updates the state fo the cache API.
515 public function set_state($state) {
516 if ($state <= $this->state) {
519 $this->state = $state;
524 * Informs the factory that the cache is currently updating itself.
526 * This forces the state to upgrading and can only be called once the cache is ready to use.
527 * Calling it ensure we don't try to reinstantite things when requesting cache definitions that don't exist yet.
529 public function updating_started() {
530 if ($this->state !== self::STATE_READY) {
533 $this->state = self::STATE_UPDATING;
538 * Informs the factory that the upgrading has finished.
540 * This forces the state back to ready.
542 public function updating_finished() {
543 $this->state = self::STATE_READY;
547 * Returns true if the cache API has been disabled.
551 public function is_disabled() {
552 return $this->state === self::STATE_DISABLED;
556 * Returns true if the cache is currently initialising itself.
558 * This includes both initialisation and saving the cache config file as part of that initialisation.
562 public function is_initialising() {
563 return $this->state === self::STATE_INITIALISING || $this->state === self::STATE_SAVING;
567 * Returns true if the cache is currently updating itself.
571 public function is_updating() {
572 return $this->state === self::STATE_UPDATING;
576 * Disables as much of the cache API as possible.
578 * All of the magic associated with the disabled cache is wrapped into this function.
579 * In switching out the factory for the disabled factory it gains full control over the initialisation of objects
580 * and can use all of the disabled alternatives.
583 * This function has been marked as protected so that it cannot be abused through the public API presently.
584 * Perhaps in the future we will allow this, however as per the build up to the first release containing
585 * MUC it was decided that this was just to risky and abusable.
587 protected static function disable() {
589 require_once($CFG->dirroot.'/cache/disabledlib.php');
590 self::$instance = new cache_factory_disabled();
594 * Returns true if the cache stores have been disabled.
598 public function stores_disabled() {
599 return $this->state === self::STATE_STORES_DISABLED || $this->is_disabled();
603 * Disables cache stores.
605 * The cache API will continue to function however none of the actual stores will be used.
606 * Instead the dummy store will be provided for all cache requests.
607 * This is useful in situations where you cannot be sure any stores are working.
609 * In order to re-enable the cache you must call the cache factories static reset method:
611 * // Disable the cache factory.
612 * cache_factory::disable_stores();
613 * // Re-enable the cache factory by resetting it.
614 * cache_factory::reset();
617 public static function disable_stores() {
618 // First reset to clear any static acceleration array.
619 $factory = self::instance();
620 $factory->reset_cache_instances();
621 $factory->set_state(self::STATE_STORES_DISABLED);