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 * The library file for the memcache cache store.
20 * This file is part of the memcache cache store, it contains the API for interacting with an instance of the store.
22 * @package cachestore_memcache
23 * @copyright 2012 Sam Hemelryk
24 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
27 defined('MOODLE_INTERNAL') || die();
30 * The memcache store class.
32 * (Not to be confused with memcached store)
34 * Configuration options:
35 * servers: string: host:port:weight , ...
37 * @copyright 2012 Sam Hemelryk
38 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
40 class cachestore_memcache extends cache_store_base {
43 * The name of the store
49 * The memcache connection once established.
52 protected $connection;
55 * An array of servers to use in the connection args.
58 protected $servers = array();
61 * An array of options used when establishing the connection.
64 protected $options = array();
67 * Set to true when things are ready to be initialised.
70 protected $isready = false;
73 * The cache definition this store was initialised for.
74 * @var cache_definition
76 protected $definition;
79 * Constructs the store instance.
81 * Noting that this function is not an initialisation. It is used to prepare the store for use.
82 * The store will be initialised when required and will be provided with a cache_definition at that time.
85 * @param array $configuration
87 public function __construct($name, array $configuration = array()) {
89 if (!array_key_exists('servers', $configuration) || empty($configuration['servers'])) {
90 // Nothing configured.
93 if (!is_array($configuration['servers'])) {
94 $configuration['servers'] = array($configuration['servers']);
96 foreach ($configuration['servers'] as $server) {
97 if (!is_array($server)) {
98 $server = explode(':', $server, 3);
100 if (!array_key_exists(1, $server)) {
103 } else if (!array_key_exists(2, $server)) {
106 $this->servers[] = $server;
109 $this->isready = true;
113 * Initialises the cache.
115 * Once this has been done the cache is all set to be used.
117 * @param cache_definition $definition
119 public function initialise(cache_definition $definition) {
120 if ($this->is_initialised()) {
121 throw new coding_exception('This memcache instance has already been initialised.');
123 $this->definition = $definition;
124 $this->connection = new Memcache;
125 foreach ($this->servers as $server) {
126 $this->connection->addServer($server[0], $server[1], true, $server[2]);
131 * Returns true once this instance has been initialised.
135 public function is_initialised() {
136 return ($this->connection !== null);
140 * Returns true if this store instance is ready to be used.
143 public function is_ready() {
144 return $this->isready;
148 * Returns true if the store requirements are met.
152 public static function are_requirements_met() {
153 return class_exists('Memcache');
157 * Returns true if the given mode is supported by this store.
159 * @param int $mode One of cache_store::MODE_*
162 public static function is_supported_mode($mode) {
163 return ($mode === self::MODE_APPLICATION || $mode === self::MODE_SESSION);
167 * Returns the supported features as a combined int.
169 * @param array $configuration
172 public static function get_supported_features(array $configuration = array()) {
173 return self::SUPPORTS_NATIVE_TTL;
177 * Returns the supported modes as a combined int.
179 * @param array $configuration
182 public static function get_supported_modes(array $configuration = array()) {
183 return self::MODE_APPLICATION + self::MODE_SESSION;
187 * Retrieves an item from the cache store given its key.
189 * @param string $key The key to retrieve
190 * @return mixed The data that was associated with the key, or false if the key did not exist.
192 public function get($key) {
193 return $this->connection->get($key);
197 * Retrieves several items from the cache store in a single transaction.
199 * If not all of the items are available in the cache then the data value for those that are missing will be set to false.
201 * @param array $keys The array of keys to retrieve
202 * @return array An array of items from the cache. There will be an item for each key, those that were not in the store will
205 public function get_many($keys) {
206 $result = $this->connection->get($keys);
207 if (!is_array($result)) {
210 foreach ($keys as $key) {
211 if (!array_key_exists($key, $result)) {
212 $result[$key] = false;
219 * Sets an item in the cache given its key and data value.
221 * @param string $key The key to use.
222 * @param mixed $data The data to set.
223 * @return bool True if the operation was a success false otherwise.
225 public function set($key, $data) {
226 return $this->connection->set($key, $data, MEMCACHE_COMPRESSED, $this->definition->get_ttl());
230 * Sets many items in the cache in a single transaction.
232 * @param array $keyvaluearray An array of key value pairs. Each item in the array will be an associative array with two
233 * keys, 'key' and 'value'.
234 * @return int The number of items successfully set. It is up to the developer to check this matches the number of items
235 * sent ... if they care that is.
237 public function set_many(array $keyvaluearray) {
239 foreach ($keyvaluearray as $pair) {
240 if ($this->connection->set($pair['key'], $pair['value'], MEMCACHE_COMPRESSED, $this->definition->get_ttl())) {
248 * Deletes an item from the cache store.
250 * @param string $key The key to delete.
251 * @return bool Returns true if the operation was a success, false otherwise.
253 public function delete($key) {
254 return $this->connection->delete($key);
258 * Deletes several keys from the cache in a single action.
260 * @param array $keys The keys to delete
261 * @return int The number of items successfully deleted.
263 public function delete_many(array $keys) {
265 foreach ($keys as $key) {
266 if ($this->delete($key)) {
274 * Purges the cache deleting all items within it.
276 * @return boolean True on success. False otherwise.
278 public function purge() {
279 $this->connection->flush();
284 * Given the data from the add instance form this function creates a configuration array.
286 * @param stdClass $data
289 public static function config_get_configuration_array($data) {
290 $lines = explode("\n", $data->servers);
292 foreach ($lines as $line) {
293 $line = trim($line, ':');
294 $servers[] = explode(':', $line, 3);
297 'servers' => $servers,
302 * Allows the cache store to set its data against the edit form before it is shown to the user.
304 * @param moodleform $editform
305 * @param array $config
307 public static function config_set_edit_form_data(moodleform $editform, array $config) {
309 if (!empty($config['servers'])) {
311 foreach ($config['servers'] as $server) {
312 $servers[] = join(":", $server);
314 $data['servers'] = join("\n", $servers);
316 $editform->set_data($data);
320 * Performs any necessary clean up when the store instance is being deleted.
322 public function cleanup() {
327 * Generates an instance of the cache store that can be used for testing.
329 * @param cache_definition $definition
332 public static function initialise_test_instance(cache_definition $definition) {
333 if (!self::are_requirements_met()) {
337 $config = get_config('cachestore_memcache');
338 if (empty($config->testservers)) {
342 $configuration = array();
343 $configuration['servers'] = explode("\n", $config->testservers);
345 $store = new cachestore_memcache('Test memcache', $configuration);
346 $store->initialise($definition);
352 * Returns the name of this instance.
355 public function my_name() {