MDL-36466 cache: implemented functionality to disable the bulk of the cache API
[moodle.git] / cache / README.md
CommitLineData
4075433b
SH
1Moodle Universal Cache / Cache API
2==================================
8139ad13
SH
3
4Sample code snippets
5--------------------
6
7A definition:
8
9 $definitions = array(
4075433b 10 'string' => array( // Required, unique to the component
8139ad13 11 'mode' => cache_store::MODE_APPLICATION, // Required
47834bcd 12 'simplekeys' => false, // Optional
2e1e266c 13 'simpledata' => false, // Optional
8139ad13 14 'requireidentifiers' => array( // Optional
4075433b 15 'lang'
8139ad13
SH
16 ),
17 'requiredataguarantee' => false, // Optional
18 'requiremultipleidentifiers' => false, // Optional
fe352208
SH
19 'requirelockingread' => false, // Optional
20 'requirelockingwrite' => false, // Optional
21 'maxsize' => null, // Optional
8139ad13
SH
22 'overrideclass' => null, // Optional
23 'overrideclassfile' => null, // Optional
24 'datasource' => null, // Optional
25 'datasourcefile' => null, // Optional
26 'persistent' => false, // Optional
fe352208 27 'persistentmaxsize' => false, // Optional
8139ad13
SH
28 'ttl' => 0, // Optional
29 'mappingsonly' => false // Optional
30 'invalidationevents' => array( // Optional
31 'contextmarkeddirty'
32 ),
33 )
34 );
35
fe352208 36Getting something from a cache using the definition:
8139ad13
SH
37
38 $cache = cache::make('core', 'string');
39 if (!$component = $cache->get('component')) {
40 // get returns false if its not there and can't be loaded.
41 $component = generate_data();
42 $cache->set($component);
43 }
44
fe352208 45The same thing but using params:
8139ad13
SH
46
47 $cache = cache::make_from_params(cache_store::MODE_APPLICATION, 'core', 'string');
48 if (!$component = $cache->get('component')) {
49 // get returns false if its not there and can't be loaded.
50 $component = generate_data();
51 $cache->set($component);
52 }
53
fe352208 54If a data source had been specified in the definition, the following would be all that was needed.
8139ad13
SH
55
56 $cache = cache::make('core', 'string');
57 $component = $cache->get('component');
58
82afd05c
SH
59Disabling the cache stores.
60There are times in code when you will want to disable the cache stores.
61While 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.
62
63 // Disable the cache store at the start of your script with:
64 define('CACHE_DISABLE_STORES', true);
65
66 // Disable the cache within your script when you want with:
67 cache_factory::disable_stores();
68 // If you disabled it using the above means you can re-enable it with:
69 cache_factory::reset();
70
3680c61a
SH
71Disabling the cache entirely.
72Like 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.
73When 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.
74These disabled classes do the least work possible and through this means we avoid all manner of intialisation and configuration.
75Once disabled its not recommened to reneable the Cache API. Instead if you need it, redirect.
76
77 // To disable the cache entirely call the following:
78 cache_factory::disable();
82afd05c 79
fe352208
SH
80Cache API parts
81---------------
8139ad13 82
4075433b 83There are several parts that make up the Cache API.
8139ad13
SH
84
85### Loader
86The loader is central to the whole thing.
87It is used by the end developer to get an object that handles caching.
fe352208
SH
8890% of end developers will not need to know or use anything else in the cache API.
89In order to get a loader you must use one of two static methods, make or make_with_params.
90The loader has been kept as simple as possible, interaction is summarised by the cache_loader interface.
8139ad13 91Internally there is lots of magic going on. The important parts to know about are:
fe352208
SH
92* 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.
93* A loader is passed three things when being constructed, a definition, a store, and another loader or datasource if there is either.
8139ad13 94* If a loader is the third arg then requests will be chained to provide redundancy.
fe352208
SH
95* 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.
96* There are three core loaders. One for each application, session and request.
97* 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
98* The loader handles ttl (time to live) for stores that don't natively support ttl.
8139ad13
SH
99* The application loader handles locking for stores that don't natively support locking.
100
101### Store
102The store is the bridge between the cache API and a cache solution.
103Cache store plugins exist within moodle/cache/store.
104The 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).
105The following points highlight things you should know about stores.
106* A cache_store interface is used to define the requirements of a store plugin.
107* The store plugin can inherit the cache_is_lockable interface to handle its own locking.
108* The store plugin can inherit the cache_is_key_aware interface to handle is own has checks.
109* Store plugins inform the cache API about the things they support. Features can be required by a definition.
110** 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.
111** Multiple identifiers - Rather than a single string key, the parts that make up the key are passed as an array.
fe352208 112** 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.
8139ad13
SH
113
114### Definition
115_Definitions were not a part of the previous proposal._
116Definitions are cache definitions. They will be located within a new file for each component/plugin at **db/caches.php**.
117They 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.
fe352208 118It 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.
8139ad13
SH
119When getting a loader you can either provide a definition name, or a set or params.
120* If you provide a definition name then the matching definition is found and used to construct a loader for you.
fe352208 121* 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.
8139ad13
SH
122
123Definitions are designed to be used in situations where things are more than basic.
124
125The following settings are required for a definition:
126* name - Identifies the definition and must be unique.
fe352208 127* mode - Application, session or request.
8139ad13
SH
128
129The following optional settings can also be defined:
47834bcd 130* 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.
2e1e266c 131* 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.
8139ad13
SH
132* requireidentifiers - Any identifiers the definition requires. Must be provided when creating the loader.
133* requiredataguarantee - If set to true then only stores that support data guarantee will be used.
134* requiremultipleidentifiers - If set to true then only stores that support multiple identifiers will be used.
fe352208
SH
135* 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.
136* requirelockingwrite - If set to true a lock will be acquired before writing to the cache. Avoid this unless necessary.
137* 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.
138* overrideclass - If provided this class will be used for the loader. It must extend one of the core loader classes (based upon mode).
8139ad13
SH
139* overrideclassfile - Included if required when using the overrideclass param.
140* datasource - If provided this class will be used as a data source for the definition. It must implement the cache_data_source interface.
141* datasourcefile - Included if required when using the datasource param.
142* persistent - If set to true the loader will be stored when first created and provided to subsequent requests. More on this later.
fe352208 143* persistentmaxsize - If set to an int this will be the maximum number of items stored in the persistent cache.
8139ad13
SH
144* ttl - Can be used to set a ttl value for data being set for this cache.
145* mappingsonly - This definition can only be used if there is a store mapping for it. More on this later.
146* invalidationevents - An array of events that should trigger this cache to invalidate.
147
fe352208 148It'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.
4075433b 149
8139ad13
SH
150The persist option.
151As noted the persist option causes the loader generated for this definition to be stored when first created. Subsequent requests for this definition will be given the original loader instance.
152Data passed to or retrieved from the loader and its chained loaders gets cached by the instance.
153This option should be used when you know you will require the loader several times and perhaps in different areas of code.
154Because 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.
155It should be used sparingly.
156
157The mappingsonly option.
158The administrator of a site can create mappings between stores and definitions. Allowing them to designate stores for specific definitions (caches).
159Setting this option to true means that the definition can only be used if a mapping has been made for it.
160Normally if no mappings exist then the default store for the definition mode is used.
161
162### Data source
163Data sources allow cache _misses_ (requests for a key that doesn't exist) to be handled and loaded internally.
164The 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.
165They can be specified in a cache definition and must implement the cache_data_source interface.
166
167### How it all chains together.
fe352208 168Consider the following:
8139ad13
SH
169
170Basic request for information (no frills):
171
172 => Code calls get
173 => Loader handles get, passes the request to its store
174 <= Memcache doesn't have the data. sorry.
175 <= Loader returns the result.
176 |= Code couldn't get the data from the cache. It must generate it and then ask the loader to cache it.
177
178Advanced initial request for information not already cached (has chained stores and data source):
179
180 => Code calls get
181 => Loader handles get, passes the request to its store
182 => Memcache handles request, doesn't have it passes it to the chained store
183 => File (default store) doesn't have it requests it from the loader
184 => Data source - makes required db calls, processes information
185 ...database calls...
186 ...processing and moulding...
187 <= Data source returns the information
188 <= File caches the information on its way back through
189 <= Memcache caches the information on its way back through
190 <= Loader returns the data to the user.
191 |= Code the code now has the data.
192
193Subsequent request for information:
194
195 => Code calls get
196 => Loader handles get, passes the request to its store
197 <= Store returns the data
198 <= Loader returns the data
199 |= Code has the data
200
201Other internal magic you should be aware of
202-------------------------------------------
fe352208 203The following should fill you in on a bit more of the behind-the-scenes stuff for the cache API.
8139ad13
SH
204
205### Helper class
206There is a helper class called cache_helper which is abstract with static methods.
207This class handles much of the internal generation and initialisation requirements.
208In normal use this class will not be needed outside of the API (mostly internal use only)
209
210### Configuration
211There are two configuration classes cache_config and cache_config_writer.
212The reader class is used for every request, the writer is only used when modifying the configuration.
213Because the cache API is designed to cache database configuration and meta data it must be able to operate prior to database configuration being loaded.
214To get around this we store the configuration information in a file in the dataroot.
215The configuration file contains information on the configured store instances, definitions collected from definition files, and mappings.
216That information is stored and loaded in the same way we work with the lang string files.
217This means that we use the cache API as soon as it has been included.
218
219### Invalidation
220Cache information can be invalidated in two ways.
2211. pass a definition name and the keys to be invalidated (or none to invalidate the whole cache).
2222. pass an event and the keys to be invalidated.
223
fe352208 224The first method is designed to be used when you have a single known definition you want to invalidate entries within.
8139ad13
SH
225The 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).
226When 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.
fe352208 227This is obviously a recursive, and therefore, intense process.