1 Moodle Universal Cache / Cache API
2 ==================================
10 'string' => array( // Required, unique to the component
11 'mode' => cache_store::MODE_APPLICATION, // Required
12 'simplekeys' => false, // Optional
13 'simpledata' => false, // Optional
14 'requireidentifiers' => array( // Optional
17 'requiredataguarantee' => false, // Optional
18 'requiremultipleidentifiers' => false, // Optional
19 'requirelockingread' => false, // Optional
20 'requirelockingwrite' => false, // Optional
21 'requiresearchable' => false, // Optional
22 'maxsize' => null, // Optional
23 'overrideclass' => null, // Optional
24 'overrideclassfile' => null, // Optional
25 'datasource' => null, // Optional
26 'datasourcefile' => null, // Optional
27 'staticacceleration' => false, // Optional
28 'staticaccelerationsize' => false, // Optional
29 'ttl' => 0, // Optional
30 'mappingsonly' => false // Optional
31 'invalidationevents' => array( // Optional
34 'sharingoptions' => null // Optional
35 'defaultsharing' => null // Optional
39 Getting something from a cache using the definition:
41 $cache = cache::make('core', 'string');
42 if (!$component = $cache->get('component')) {
43 // get returns false if its not there and can't be loaded.
44 $component = generate_data();
45 $cache->set($component);
48 The same thing but using params:
50 $cache = cache::make_from_params(cache_store::MODE_APPLICATION, 'core', 'string');
51 if (!$component = $cache->get('component')) {
52 // get returns false if its not there and can't be loaded.
53 $component = generate_data();
54 $cache->set($component);
57 If a data source had been specified in the definition, the following would be all that was needed.
59 $cache = cache::make('core', 'string');
60 $component = $cache->get('component');
62 Disabling the cache stores.
63 There are times in code when you will want to disable the cache stores.
64 While the cache API must still be functional in order for calls to it to work it is possible to disable the use of the cache stores separately so that you can be sure only the cache will function in all circumstances.
66 // Disable the cache store at the start of your script with:
67 define('CACHE_DISABLE_STORES', true);
69 // Disable the cache within your script when you want with:
70 cache_factory::disable_stores();
71 // If you disabled it using the above means you can re-enable it with:
72 cache_factory::reset();
74 Disabling the cache entirely.
75 Like above there are times when you want the cache to avoid initialising anything it doesn't absolutely need. Things such as installation and upgrade require this functionality.
76 When the cache API is disabled it is still functional however special "disabled" classes will be used instead of the regular classes that make the Cache API tick.
77 These disabled classes do the least work possible and through this means we avoid all manner of intialisation and configuration.
78 Once disabled it cannot be re-enabled.
80 // To disable the cache entirely call the following:
81 define('CACHE_DISABLE_ALL', true);
86 There are several parts that make up the Cache API.
89 The loader is central to the whole thing.
90 It is used by the end developer to get an object that handles caching.
91 90% of end developers will not need to know or use anything else in the cache API.
92 In order to get a loader you must use one of two static methods, make or make_from_params.
93 The loader has been kept as simple as possible, interaction is summarised by the cache_loader interface.
94 Internally there is lots of magic going on. The important parts to know about are:
95 * There are two ways to get a loader, the first with a definition (discussed below) the second with params. When params are used they are turned into an adhoc definition with default params.
96 * A loader is passed three things when being constructed, a definition, a store, and another loader or datasource if there is either.
97 * If a loader is the third arg then requests will be chained to provide redundancy.
98 * If a data source is provided then requests for an item that is not cached will be passed to the data source and that will be expected to load the data. If it loads data, that data is stored in each store on its way back to the user.
99 * There are three core loaders. One for each application, session and request.
100 * A custom loader can be used. It will be provided by the definition (thus cannot be used with ad hoc definitions) and must override the appropriate core loader
101 * The loader handles ttl (time to live) for stores that don't natively support ttl.
102 * The application loader handles locking for stores that don't natively support locking.
105 The store is the bridge between the cache API and a cache solution.
106 Cache store plugins exist within moodle/cache/store.
107 The administrator of a site can configure multiple instances of each plugin, the configuration gets initialised as a store for the loader when required in code (during construction of the loader).
108 The following points highlight things you should know about stores.
109 * A cache_store interface is used to define the requirements of a store plugin.
110 * The store plugin can inherit the cache_is_lockable interface to handle its own locking.
111 * The store plugin can inherit the cache_is_key_aware interface to handle is own has checks.
112 * Store plugins inform the cache API about the things they support. Features can be required by a definition.
113 * Data guarantee - Data is guaranteed to exist in the cache once it is set there. It is never cleaned up to free space or because it has not been recently used.
114 * Multiple identifiers - Rather than a single string key, the parts that make up the key are passed as an array.
115 * Native TTL support - When required, the store supports native ttl and doesn't require the cache API to manage ttl of things given to the store.
116 * There are two reserved store names, base and dummy. These are both used internally.
119 _Definitions were not a part of the previous proposal._
120 Definitions are cache definitions. They will be located within a new file for each component/plugin at **db/caches.php**.
121 They can be used to set all of the requirements of a cache instance and are used to ensure that a cache can only be interacted with in the same way no matter where it is being used.
122 It also ensures that caches are easy to use, the config is stored in the definition and the developer using the cache does not need to know anything about its inner workings.
123 When getting a loader you can either provide a definition name, or a set or params.
124 * If you provide a definition name then the matching definition is found and used to construct a loader for you.
125 * If you provide params then an ad hoc definition is created. It will have defaults and will not have any special requirements or options set.
127 Definitions are designed to be used in situations where things are more than basic.
129 The following settings are required for a definition:
130 * name - Identifies the definition and must be unique.
131 * mode - Application, session or request.
133 The following optional settings can also be defined:
134 * simplekeys - Set to true if items will always and only have simple keys. Simple keys may contain a-zA-Z0-9_. If set to true we use the keys as they are without hashing them. Good for performance and possible because we know the keys are safe.
135 * simpledata - Set to true if you know that you will only be storing scalar values or arrays of scalar values. Avoids costly investigation of data types.
136 * requireidentifiers - Any identifiers the definition requires. Must be provided when creating the loader.
137 * requiredataguarantee - If set to true then only stores that support data guarantee will be used.
138 * requiremultipleidentifiers - If set to true then only stores that support multiple identifiers will be used.
139 * requirelockingread - If set to true a lock will be acquired for reading. Don't use this setting unless you have a REALLY good reason to.
140 * requirelockingwrite - If set to true a lock will be acquired before writing to the cache. Avoid this unless necessary.
141 * requiresearchable - If set to true only stores that support key searching will be used for this definition. Its not recommended to use this unless absolutely unavoidable.
142 * maxsize - This gives a cache an indication about the maximum items it should store. Cache stores don't have to use this, it is up to them to decide if its required.
143 * overrideclass - If provided this class will be used for the loader. It must extend one of the core loader classes (based upon mode).
144 * overrideclassfile - Included if required when using the overrideclass param.
145 * datasource - If provided this class will be used as a data source for the definition. It must implement the cache_data_source interface.
146 * datasourcefile - Included if required when using the datasource param.
147 * staticacceleration - Any data passing through the cache will be held onto to make subsequent requests for it faster.
148 * staticaccelerationsize - If set to an int this will be the maximum number of items stored in the static acceleration array.
149 * ttl - Can be used to set a ttl value for data being set for this cache.
150 * mappingsonly - This definition can only be used if there is a store mapping for it. More on this later.
151 * invalidationevents - An array of events that should trigger this cache to invalidate.
152 * sharingoptions - The sum of the possible sharing options that are applicable to the definition. An advanced setting.
153 * defaultsharing - The default sharing option to use. It's highly recommended that you don't set this unless there is a very specific reason not to use the system default.
155 It's important to note that internally the definition is also aware of the component. This is picked up when the definition is read, based upon the location of the caches.php file.
157 The staticacceleration option.
158 Data passed to or retrieved from the loader and its chained loaders gets cached by the instance.
159 Because it caches key=>value data it avoids the need to re-fetch things from stores after the first request. Its good for performance, bad for memory.
160 Memory use can be controlled by setting the staticaccelerationsize option.
161 It should be used sparingly.
163 The mappingsonly option.
164 The administrator of a site can create mappings between stores and definitions. Allowing them to designate stores for specific definitions (caches).
165 Setting this option to true means that the definition can only be used if a mapping has been made for it.
166 Normally if no mappings exist then the default store for the definition mode is used.
169 This controls the options available to the user when configuring the sharing of a definitions cached data.
170 By default all sharing options are available to select. This particular option allows the developer to limit the options available to the admin configuring the cache.
173 Data sources allow cache _misses_ (requests for a key that doesn't exist) to be handled and loaded internally.
174 The loader gets used as the last resort if provided and means that code using the cache doesn't need to handle the situation that information isn't cached.
175 They can be specified in a cache definition and must implement the cache_data_source interface.
177 ### How it all chains together.
178 Consider the following:
180 Basic request for information (no frills):
183 => Loader handles get, passes the request to its store
184 <= Memcache doesn't have the data. sorry.
185 <= Loader returns the result.
186 |= Code couldn't get the data from the cache. It must generate it and then ask the loader to cache it.
188 Advanced initial request for information not already cached (has chained stores and data source):
191 => Loader handles get, passes the request to its store
192 => Memcache handles request, doesn't have it passes it to the chained store
193 => File (default store) doesn't have it requests it from the loader
194 => Data source - makes required db calls, processes information
196 ...processing and moulding...
197 <= Data source returns the information
198 <= File caches the information on its way back through
199 <= Memcache caches the information on its way back through
200 <= Loader returns the data to the user.
201 |= Code the code now has the data.
203 Subsequent request for information:
206 => Loader handles get, passes the request to its store
207 <= Store returns the data
208 <= Loader returns the data
211 Other internal magic you should be aware of
212 -------------------------------------------
213 The following should fill you in on a bit more of the behind-the-scenes stuff for the cache API.
216 There is a helper class called cache_helper which is abstract with static methods.
217 This class handles much of the internal generation and initialisation requirements.
218 In normal use this class will not be needed outside of the API (mostly internal use only)
221 There are two configuration classes cache_config and cache_config_writer.
222 The reader class is used for every request, the writer is only used when modifying the configuration.
223 Because the cache API is designed to cache database configuration and meta data it must be able to operate prior to database configuration being loaded.
224 To get around this we store the configuration information in a file in the dataroot.
225 The configuration file contains information on the configured store instances, definitions collected from definition files, and mappings.
226 That information is stored and loaded in the same way we work with the lang string files.
227 This means that we use the cache API as soon as it has been included.
230 Cache information can be invalidated in two ways.
231 1. pass a definition name and the keys to be invalidated (or none to invalidate the whole cache).
232 2. pass an event and the keys to be invalidated.
234 The first method is designed to be used when you have a single known definition you want to invalidate entries within.
235 The second method is a lot more intensive for the system. There are defined invalidation events that definitions can "subscribe" to (through the definitions invalidationevents option).
236 When you invalidate by event the cache API finds all of the definitions that subscribe to the event, it then loads the stores for each of those definitions and purges the keys from each store.
237 This is obviously a recursive, and therefore, intense process.
240 Both the cache API and the cache stores have unit tests.
241 Please be aware that several of the cache stores require configuration in order to be able operate in the unit tests.
242 Tests for stores requiring configuration that havn't been configured will be skipped.
243 All configuration is done in your sites config.php through definitions.
244 The following snippet illustates how to configure the three core cache stores that require configuration.
246 define('TEST_CACHESTORE_MEMCACHE_TESTSERVERS', '127.0.0.1:11211');
247 define('TEST_CACHESTORE_MEMCACHED_TESTSERVERS', '127.0.0.1:11211');
248 define('TEST_CACHESTORE_MONGODB_TESTSERVER', 'mongodb://localhost:27017');
250 Please be aware that if you are using Memcache or Memcached it is recommended to use dedicated Memcached servers.
251 When caches get purged the memcached servers you have configured get purged, any data stored within them whether it belongs to Moodle or not will be removed.
252 If you are using Memcached for sessions as well as caching/testing and caches get purged your sessions will be removed prematurely and users will be need to start again.