MemcachedDriver.php 5.07 KB
Newer Older
Scott committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
<?php
/*
	Question2Answer by Gideon Greenspan and contributors
	http://www.question2answer.org/

	File: qa-include/Q2A/Storage/MemcachedDriver.php
	Description: Memcached-based driver for caching system.


	This program is free software; you can redistribute it and/or
	modify it under the terms of the GNU General Public License
	as published by the Free Software Foundation; either version 2
	of the License, or (at your option) any later version.

	This program is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU General Public License for more details.

	More about this license: http://www.question2answer.org/license.php
*/

/**
 * Caches data (typically from database queries) in memory using Memcached.
 */
class Q2A_Storage_MemcachedDriver implements Q2A_Storage_CacheDriver
{
	private $memcached;
	private $enabled = false;
30
	private $keyPrefix = '';
Scott committed
31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
	private $error;
	private $flushed = false;

	const HOST = '127.0.0.1';
	const PORT = 11211;

	/**
	 * Creates a new Memcached instance and checks we can cache items.
	 * @param array $config Configuration data, including cache storage directory.
	 *
	 * @return void
	 */
	public function __construct($config)
	{
		if (!$config['enabled']) {
			return;
		}

49 50 51 52
		if (isset($config['keyprefix'])) {
			$this->keyPrefix = $config['keyprefix'];
		}

Scott committed
53 54 55
		if (extension_loaded('memcached')) {
			$this->memcached = new Memcached;
			$this->memcached->addServer(self::HOST, self::PORT);
56
			if ($this->memcached->set($this->keyPrefix . 'test', 'TEST')) {
Scott committed
57 58 59 60 61
				$this->enabled = true;
			} else {
				$this->setMemcachedError();
			}
		} else {
Scott committed
62
			$this->error = qa_lang_html('admin/no_memcached');
Scott committed
63 64 65 66 67 68 69 70 71 72 73 74 75 76 77
		}
	}

	/**
	 * Get the cached data for the supplied key. Data can be any format but is usually an array.
	 * @param string $key The unique cache identifier.
	 *
	 * @return mixed The cached data, or null otherwise.
	 */
	public function get($key)
	{
		if (!$this->enabled) {
			return null;
		}

78
		$result = $this->memcached->get($this->keyPrefix . $key);
Scott committed
79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103

		if ($result === false) {
			$this->setMemcachedError();
			return null;
		}

		return $result;
	}

	/**
	 * Store something in the cache along with the key and expiry time. Data gets 'serialized' to a string before storing.
	 * @param string $key The unique cache identifier.
	 * @param mixed $data The data to cache (in core Q2A this is usually an array).
	 * @param int $ttl Number of minutes for which to cache the data.
	 *
	 * @return bool Whether the file was successfully cached.
	 */
	public function set($key, $data, $ttl)
	{
		if (!$this->enabled) {
			return false;
		}

		$ttl = (int) $ttl;
		$expiry = time() + ($ttl * 60);
104
		$success = $this->memcached->set($this->keyPrefix . $key, $data, $expiry);
Scott committed
105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124

		if (!$success) {
			$this->setMemcachedError();
		}

		return $success;
	}

	/**
	 * Delete an item from the cache.
	 * @param string $key The unique cache identifier.
	 *
	 * @return bool Whether the operation succeeded.
	 */
	public function delete($key)
	{
		if (!$this->enabled) {
			return false;
		}

125
		$success = $this->memcached->delete($this->keyPrefix . $key);
Scott committed
126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176

		if (!$success) {
			$this->setMemcachedError();
		}

		return $success;
	}

	/**
	 * Delete multiple items from the cache.
	 * @param int $limit Maximum number of items to process. 0 = unlimited
	 * @param int $start Offset from which to start (used for 'batching' deletes).
	 * @param bool $expiredOnly This parameter is ignored because Memcached automatically clears expired items.
	 *
	 * @return int Number of files deleted. For Memcached we return 0
	 */
	public function clear($limit = 0, $start = 0, $expiredOnly = false)
	{
		if ($this->enabled && !$expiredOnly && !$this->flushed) {
			$success = $this->memcached->flush();
			// avoid multiple calls to flush()
			$this->flushed = true;

			if (!$success) {
				$this->setMemcachedError();
			}
		}

		return 0;
	}

	/**
	 * Whether caching is available.
	 *
	 * @return bool
	 */
	public function isEnabled()
	{
		return $this->enabled;
	}

	/**
	 * Get the last error.
	 *
	 * @return string
	 */
	public function getError()
	{
		return $this->error;
	}

177 178 179 180 181 182 183 184 185 186
	/**
	 * Get the prefix used for all cache keys.
	 *
	 * @return string
	 */
	public function getKeyPrefix()
	{
		return $this->keyPrefix;
	}

Scott committed
187 188 189 190 191 192 193
	/**
	 * Get current statistics for the cache.
	 *
	 * @return array Array of stats: 'files' => number of files, 'size' => total file size in bytes.
	 */
	public function getStats()
	{
194 195
		$totalFiles = 0;
		$totalBytes = 0;
Scott committed
196

197 198 199 200 201 202 203
		if ($this->enabled) {
			$stats = $this->memcached->getStats();
			$key = self::HOST . ':' . self::PORT;

			$totalFiles = isset($stats[$key]['curr_items']) ? $stats[$key]['curr_items'] : 0;
			$totalBytes = isset($stats[$key]['bytes']) ? $stats[$key]['bytes'] : 0;
		}
Scott committed
204 205 206 207 208 209 210 211 212 213 214 215 216 217

		return array(
			'files' => $totalFiles,
			'size' => $totalBytes,
		);
	}

	/**
	 * Set current error to Memcached result message
	 *
	 * @return void
	 */
	private function setMemcachedError()
	{
Scott committed
218
		$this->error = qa_lang_html_sub('admin/memcached_error', $this->memcached->getResultMessage());
Scott committed
219 220
	}
}