Subversion Repositories SmartDukaan

Rev

Details | Last modification | View Log | RSS feed

Rev Author Line No. Line
12345 anikendra 1
<?php
2
/**
3
 * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
4
 * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
5
 *
6
 * Licensed under The MIT License
7
 * For full copyright and license information, please see the LICENSE.txt
8
 * Redistributions of files must retain the above copyright notice.
9
 *
10
 * @copyright     Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
11
 * @link          http://cakephp.org CakePHP(tm) Project
12
 * @since         CakePHP(tm) v 2.5.0
13
 * @license       http://www.opensource.org/licenses/mit-license.php MIT License
14
 */
15
 
16
/**
17
 * Memcached storage engine for cache. Memcached has some limitations in the amount of
18
 * control you have over expire times far in the future. See MemcachedEngine::write() for
19
 * more information.
20
 *
21
 * Main advantage of this Memcached engine over the memcached engine is
22
 * support of binary protocol, and igbibnary serialization
23
 * (if memcached extension compiled with --enable-igbinary)
24
 * Compressed keys can also be incremented/decremented
25
 *
26
 * @package       Cake.Cache.Engine
27
 */
28
class MemcachedEngine extends CacheEngine {
29
 
30
/**
31
 * memcached wrapper.
32
 *
33
 * @var Memcache
34
 */
35
	protected $_Memcached = null;
36
 
37
/**
38
 * Settings
39
 *
40
 *  - servers = string or array of memcached servers, default => 127.0.0.1. If an
41
 *    array MemcacheEngine will use them as a pool.
42
 *  - compress = boolean, default => false
43
 *  - persistent = string The name of the persistent connection. All configurations using
44
 *    the same persistent value will share a single underlying connection.
45
 *  - serialize = string, default => php. The serializer engine used to serialize data.
46
 *    Available engines are php, igbinary and json. Beside php, the memcached extension
47
 *    must be compiled with the appropriate serializer support.
48
 *
49
 * @var array
50
 */
51
	public $settings = array();
52
 
53
/**
54
 * List of available serializer engines
55
 *
56
 * Memcached must be compiled with json and igbinary support to use these engines
57
 *
58
 * @var array
59
 */
60
	protected $_serializers = array(
61
		'igbinary' => Memcached::SERIALIZER_IGBINARY,
62
		'json' => Memcached::SERIALIZER_JSON,
63
		'php' => Memcached::SERIALIZER_PHP
64
	);
65
 
66
/**
67
 * Initialize the Cache Engine
68
 *
69
 * Called automatically by the cache frontend
70
 * To reinitialize the settings call Cache::engine('EngineName', [optional] settings = array());
71
 *
72
 * @param array $settings array of setting for the engine
73
 * @return bool True if the engine has been successfully initialized, false if not
74
 * @throws CacheException when you try use authentication without Memcached compiled with SASL support
75
 */
76
	public function init($settings = array()) {
77
		if (!class_exists('Memcached')) {
78
			return false;
79
		}
80
		if (!isset($settings['prefix'])) {
81
			$settings['prefix'] = Inflector::slug(APP_DIR) . '_';
82
		}
83
 
84
		if (defined('Memcached::HAVE_MSGPACK') && Memcached::HAVE_MSGPACK) {
85
			$this->_serializers['msgpack'] = Memcached::SERIALIZER_MSGPACK;
86
		}
87
 
88
		$settings += array(
89
			'engine' => 'Memcached',
90
			'servers' => array('127.0.0.1'),
91
			'compress' => false,
92
			'persistent' => false,
93
			'login' => null,
94
			'password' => null,
95
			'serialize' => 'php'
96
		);
97
		parent::init($settings);
98
 
99
		if (!is_array($this->settings['servers'])) {
100
			$this->settings['servers'] = array($this->settings['servers']);
101
		}
102
 
103
		if (isset($this->_Memcached)) {
104
			return true;
105
		}
106
 
107
		$this->_Memcached = new Memcached($this->settings['persistent'] ? (string)$this->settings['persistent'] : null);
108
		$this->_setOptions();
109
 
110
		if (count($this->_Memcached->getServerList())) {
111
			return true;
112
		}
113
 
114
		$servers = array();
115
		foreach ($this->settings['servers'] as $server) {
116
			$servers[] = $this->_parseServerString($server);
117
		}
118
 
119
		if (!$this->_Memcached->addServers($servers)) {
120
			return false;
121
		}
122
 
123
		if ($this->settings['login'] !== null && $this->settings['password'] !== null) {
124
			if (!method_exists($this->_Memcached, 'setSaslAuthData')) {
125
				throw new CacheException(
126
					__d('cake_dev', 'Memcached extension is not build with SASL support')
127
				);
128
			}
129
			$this->_Memcached->setSaslAuthData($this->settings['login'], $this->settings['password']);
130
		}
131
 
132
		return true;
133
	}
134
 
135
/**
136
 * Settings the memcached instance
137
 *
138
 * @throws CacheException when the Memcached extension is not built with the desired serializer engine
139
 * @return void
140
 */
141
	protected function _setOptions() {
142
		$this->_Memcached->setOption(Memcached::OPT_LIBKETAMA_COMPATIBLE, true);
143
 
144
		$serializer = strtolower($this->settings['serialize']);
145
		if (!isset($this->_serializers[$serializer])) {
146
			throw new CacheException(
147
				__d('cake_dev', '%s is not a valid serializer engine for Memcached', $serializer)
148
			);
149
		}
150
 
151
		if ($serializer !== 'php' && !constant('Memcached::HAVE_' . strtoupper($serializer))) {
152
			throw new CacheException(
153
				__d('cake_dev', 'Memcached extension is not compiled with %s support', $serializer)
154
			);
155
		}
156
 
157
		$this->_Memcached->setOption(Memcached::OPT_SERIALIZER, $this->_serializers[$serializer]);
158
 
159
		// Check for Amazon ElastiCache instance
160
		if (defined('Memcached::OPT_CLIENT_MODE') && defined('Memcached::DYNAMIC_CLIENT_MODE')) {
161
			$this->_Memcached->setOption(Memcached::OPT_CLIENT_MODE, Memcached::DYNAMIC_CLIENT_MODE);
162
		}
163
 
164
		$this->_Memcached->setOption(Memcached::OPT_COMPRESSION, (bool)$this->settings['compress']);
165
	}
166
 
167
/**
168
 * Parses the server address into the host/port. Handles both IPv6 and IPv4
169
 * addresses and Unix sockets
170
 *
171
 * @param string $server The server address string.
172
 * @return array Array containing host, port
173
 */
174
	protected function _parseServerString($server) {
175
		if ($server[0] === 'u') {
176
			return array($server, 0);
177
		}
178
		if (substr($server, 0, 1) === '[') {
179
			$position = strpos($server, ']:');
180
			if ($position !== false) {
181
				$position++;
182
			}
183
		} else {
184
			$position = strpos($server, ':');
185
		}
186
		$port = 11211;
187
		$host = $server;
188
		if ($position !== false) {
189
			$host = substr($server, 0, $position);
190
			$port = substr($server, $position + 1);
191
		}
192
		return array($host, (int)$port);
193
	}
194
 
195
/**
196
 * Write data for key into cache. When using memcached as your cache engine
197
 * remember that the Memcached pecl extension does not support cache expiry times greater
198
 * than 30 days in the future. Any duration greater than 30 days will be treated as never expiring.
199
 *
200
 * @param string $key Identifier for the data
201
 * @param mixed $value Data to be cached
202
 * @param int $duration How long to cache the data, in seconds
203
 * @return bool True if the data was successfully cached, false on failure
204
 * @see http://php.net/manual/en/memcache.set.php
205
 */
206
	public function write($key, $value, $duration) {
207
		if ($duration > 30 * DAY) {
208
			$duration = 0;
209
		}
210
 
211
		return $this->_Memcached->set($key, $value, $duration);
212
	}
213
 
214
/**
215
 * Read a key from the cache
216
 *
217
 * @param string $key Identifier for the data
218
 * @return mixed The cached data, or false if the data doesn't exist, has expired, or if there was an error fetching it
219
 */
220
	public function read($key) {
221
		return $this->_Memcached->get($key);
222
	}
223
 
224
/**
225
 * Increments the value of an integer cached key
226
 *
227
 * @param string $key Identifier for the data
228
 * @param int $offset How much to increment
229
 * @return New incremented value, false otherwise
230
 * @throws CacheException when you try to increment with compress = true
231
 */
232
	public function increment($key, $offset = 1) {
233
		return $this->_Memcached->increment($key, $offset);
234
	}
235
 
236
/**
237
 * Decrements the value of an integer cached key
238
 *
239
 * @param string $key Identifier for the data
240
 * @param int $offset How much to subtract
241
 * @return New decremented value, false otherwise
242
 * @throws CacheException when you try to decrement with compress = true
243
 */
244
	public function decrement($key, $offset = 1) {
245
		return $this->_Memcached->decrement($key, $offset);
246
	}
247
 
248
/**
249
 * Delete a key from the cache
250
 *
251
 * @param string $key Identifier for the data
252
 * @return bool True if the value was successfully deleted, false if it didn't exist or couldn't be removed
253
 */
254
	public function delete($key) {
255
		return $this->_Memcached->delete($key);
256
	}
257
 
258
/**
259
 * Delete all keys from the cache
260
 *
261
 * @param bool $check If true no deletes will occur and instead CakePHP will rely
262
 *   on key TTL values.
263
 * @return bool True if the cache was successfully cleared, false otherwise
264
 */
265
	public function clear($check) {
266
		if ($check) {
267
			return true;
268
		}
269
 
270
		$keys = $this->_Memcached->getAllKeys();
271
 
272
		foreach ($keys as $key) {
273
			if (strpos($key, $this->settings['prefix']) === 0) {
274
				$this->_Memcached->delete($key);
275
			}
276
		}
277
 
278
		return true;
279
	}
280
 
281
/**
282
 * Returns the `group value` for each of the configured groups
283
 * If the group initial value was not found, then it initializes
284
 * the group accordingly.
285
 *
286
 * @return array
287
 */
288
	public function groups() {
289
		if (empty($this->_compiledGroupNames)) {
290
			foreach ($this->settings['groups'] as $group) {
291
				$this->_compiledGroupNames[] = $this->settings['prefix'] . $group;
292
			}
293
		}
294
 
295
		$groups = $this->_Memcached->getMulti($this->_compiledGroupNames);
296
		if (count($groups) !== count($this->settings['groups'])) {
297
			foreach ($this->_compiledGroupNames as $group) {
298
				if (!isset($groups[$group])) {
299
					$this->_Memcached->set($group, 1, 0);
300
					$groups[$group] = 1;
301
				}
302
			}
303
			ksort($groups);
304
		}
305
 
306
		$result = array();
307
		$groups = array_values($groups);
308
		foreach ($this->settings['groups'] as $i => $group) {
309
			$result[] = $group . $groups[$i];
310
		}
311
 
312
		return $result;
313
	}
314
 
315
/**
316
 * Increments the group value to simulate deletion of all keys under a group
317
 * old values will remain in storage until they expire.
318
 *
319
 * @param string $group The group to clear.
320
 * @return bool success
321
 */
322
	public function clearGroup($group) {
323
		return (bool)$this->_Memcached->increment($this->settings['prefix'] . $group);
324
	}
325
}