Passed
Push — master ( 165e30...00cf65 )
by Fabio
05:53
created

TMemCache::getPersistentID()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 0
dl 0
loc 3
ccs 0
cts 1
cp 0
crap 2
rs 10
c 0
b 0
f 0
1
<?php
2
/**
3
 * TMemCache class file
4
 *
5
 * @author Qiang Xue <[email protected]>
6
 * @author Carl G. Mathisen <[email protected]>
7
 * @link https://github.com/pradosoft/prado
8
 * @license https://github.com/pradosoft/prado/blob/master/LICENSE
9
 * @package Prado\Caching
10
 */
11
12
namespace Prado\Caching;
13
14
use Prado\Exceptions\TConfigurationException;
15
use Prado\Exceptions\TInvalidOperationException;
16
use Prado\Prado;
17
use Prado\TPropertyValue;
18
use Prado\Xml\TXmlElement;
19
20
/**
21
 * TMemCache class
22
 *
23
 * TMemCache implements a cache application module based on {@link http://www.danga.com/memcached/ memcached}.
24
 *
25
 * TMemCache can be configured with the Host and Port properties, which
26
 * specify the host and port of the memcache server to be used.
27
 * By default, they take the value 'localhost' and 11211, respectively.
28
 * These properties must be set before {@link init} is invoked.
29
 *
30
 * The following basic cache operations are implemented:
31
 * - {@link get} : retrieve the value with a key (if any) from cache
32
 * - {@link set} : store the value with a key into cache
33
 * - {@link add} : store the value only if cache does not have this key
34
 * - {@link delete} : delete the value with the specified key from cache
35
 * - {@link flush} : delete all values from cache
36
 *
37
 * Each value is associated with an expiration time. The {@link get} operation
38
 * ensures that any expired value will not be returned. The expiration time can
39
 * be specified by the number of seconds (maximum 60*60*24*30)
40
 * or a UNIX timestamp. A expiration time 0 represents never expire.
41
 *
42
 * By definition, cache does not ensure the existence of a value
43
 * even if it never expires. Cache is not meant to be an persistent storage.
44
 *
45
 * Also note, there is no security measure to protected data in memcache.
46
 * All data in memcache can be accessed by any process running in the system.
47
 *
48
 * To use this module, the memcached PHP extension must be loaded.
49
 *
50
 * Some usage examples of TMemCache are as follows,
51
 * <code>
52
 * $cache=new TMemCache;  // TMemCache may also be loaded as a Prado application module
53
 * $cache->init(null);
54
 * $cache->add('object',$object);
55
 * $object2=$cache->get('object');
56
 * </code>
57
 *
58
 * You can configure TMemCache two different ways. If you only need one memcache server
59
 * you may use the method as follows.
60
 * <code>
61
 * <module id="cache" class="Prado\Caching\TMemCache" Host="localhost" Port="11211" />
62
 * </code>
63
 *
64
 * If you want a more complex configuration, you may use the method as follows.
65
 * <code>
66
 * <module id="cache" class="Prado\Caching\TMemCache">
67
 *     <server Host="localhost" Port="11211" Weight="1" />
68
 *     <server Host="anotherhost" Port="11211" Weight="1" />
69
 * </module>
70
 * </code>
71
 *
72
 * If loaded, TMemCache will register itself with {@link TApplication} as the
73
 * cache module. It can be accessed via {@link TApplication::getCache()}.
74
 *
75
 * TMemCache may be configured in application configuration file as follows
76
 * <code>
77
 * <module id="cache" class="Prado\Caching\TMemCache" Host="localhost" Port="11211" />
78
 * </code>
79
 * where {@link getHost Host} and {@link getPort Port} are configurable properties
80
 * of TMemCache.
81
 *
82
 * By default the Memcached instances are destroyed at the end of the request.
83
 * To create an instance that persists between requests, set a persistent ID using
84
 * {@link setPersistentID PersistentID}.
85
 * All instances created with the same persistent_id will share the same connection.
86
 *
87
 * @author Qiang Xue <[email protected]>
88
 * @package Prado\Caching
89
 * @since 3.0
90
 */
91
class TMemCache extends TCache
92
{
93
	/**
94
	 * @var bool if the module is initialized
95
	 */
96
	private $_initialized = false;
97
	/**
98
	 * @var \Memcached the Memcached instance
99
	 */
100
	private $_cache;
101
	/**
102
	 * @var string host name of the memcache server
103
	 */
104
	private $_host = 'localhost';
105
	/**
106
	 * @var int the port number of the memcache server
107
	 */
108
	private $_port = 11211;
109
	/**
110
	 * @var array list of servers available
111
	 */
112
	private $_servers = [];
113
	/**
114
	 * @var null|string persistent id for the instance of the memcache server
115
	 */
116
	private $_persistentid = null;
117
118
	/**
119
	 * Destructor.
120
	 * Disconnect the memcache server.
121
	 */
122
	public function __destruct()
123
	{
124
		if ($this->_cache !== null) {
125
			// Quit() is available only for memcached >= 2
126
			// $this->_cache->quit();
127
		}
128
	}
129 7
130
	/**
131 7
	 * Initializes this module.
132
	 * This method is required by the IModule interface. It makes sure that
133
	 * UniquePrefix has been set, creates a Memcache instance and connects
134
	 * to the memcache server.
135 7
	 * @param TXmlElement $config configuration for this module, can be null
136
	 * @throws TConfigurationException if memcache extension is not installed or memcache sever connection fails
137
	 */
138
	public function init($config)
139
	{
140
		if (!extension_loaded('memcached')) {
141
			throw new TConfigurationException('memcached_extension_required');
142
		}
143
144
		$this->loadConfig($config);
145 17
		$this->_cache = new \Memcached($this->_persistentid);
146
		if($this->_persistentid !== null && count($this->_cache->getServerList()) > 0)
147 17
		{
148
			Prado::trace('Skipping re-adding servers for persistent id ' . $this->_persistentid, '\Prado\Caching\TMemCache');
149
		} else {
150
			if (count($this->_servers)) {
151 17
				foreach ($this->_servers as $server) {
152 17
					Prado::trace('Adding server ' . $server['Host'] . ' from serverlist', '\Prado\Caching\TMemCache');
153 17
					if ($this->_cache->addServer(
154
						$server['Host'],
155
						$server['Port'],
156
						$server['Weight']
157
					) === false) {
158
						throw new TConfigurationException('memcache_connection_failed', $server['Host'], $server['Port']);
159
					}
160
				}
161
			} else {
162
				Prado::trace('Adding server ' . $this->_host, '\Prado\Caching\TMemCache');
163
				if ($this->_cache->addServer($this->_host, $this->_port) === false) {
164
					throw new TConfigurationException('memcache_connection_failed', $this->_host, $this->_port);
165
				}
166
			}
167
		}
168 17
		$this->_initialized = true;
169 17
		parent::init($config);
170
	}
171
172
	/**
173 17
	 * Loads configuration from an XML element
174
	 * @param TXmlElement $xml configuration node
175
	 * @throws TConfigurationException if log route class or type is not specified
176 17
	 */
177 17
	private function loadConfig($xml)
178 17
	{
179
		if ($xml instanceof TXmlElement) {
0 ignored issues
show
introduced by
$xml is always a sub-type of Prado\Xml\TXmlElement.
Loading history...
180
			foreach ($xml->getElementsByTagName('server') as $serverConfig) {
181
				$properties = $serverConfig->getAttributes();
182
				if (($host = $properties->remove('Host')) === null) {
183
					throw new TConfigurationException('memcache_serverhost_required');
184
				}
185 17
				if (($port = $properties->remove('Port')) === null) {
186
					throw new TConfigurationException('memcache_serverport_required');
187 17
				}
188
				if (!is_numeric($port)) {
189
					throw new TConfigurationException('memcache_serverport_invalid');
190
				}
191
				$server = ['Host' => $host, 'Port' => $port, 'Weight' => 1];
192
				$checks = [
193
					'Weight' => 'memcache_serverweight_invalid'
194
				];
195
				foreach ($checks as $property => $exception) {
196
					$value = $properties->remove($property);
197
					if ($value !== null && is_numeric($value)) {
198
						$server[$property] = $value;
199
					} elseif ($value !== null) {
200
						throw new TConfigurationException($exception);
201
					}
202
				}
203
				$this->_servers[] = $server;
204
			}
205
		}
206
	}
207
208
	/**
209
	 * @return string host name of the memcache server
210
	 */
211
	public function getHost()
212
	{
213
		return $this->_host;
214
	}
215
216
	/**
217 17
	 * @param string $value host name of the memcache server
218
	 * @throws TInvalidOperationException if the module is already initialized
219
	 */
220
	public function setHost($value)
221
	{
222
		if ($this->_initialized) {
223
			throw new TInvalidOperationException('memcache_host_unchangeable');
224
		} else {
225
			$this->_host = $value;
226
		}
227
	}
228
229
	/**
230
	 * @return int port number of the memcache server
231
	 */
232
	public function getPort()
233
	{
234
		return $this->_port;
235
	}
236
237
	/**
238
	 * @param int $value port number of the memcache server
239
	 * @throws TInvalidOperationException if the module is already initialized
240
	 */
241
	public function setPort($value)
242
	{
243
		if ($this->_initialized) {
244
			throw new TInvalidOperationException('memcache_port_unchangeable');
245
		} else {
246
			$this->_port = TPropertyValue::ensureInteger($value);
247
		}
248
	}
249
250
	/**
251
	 * @param array $value Set internal memcached options: https://www.php.net/manual/en/memcached.constants.php
252
	 * @throws TInvalidOperationException if the module is not initialized yet
253
	 */
254
	public function setOptions($value)
255
	{
256
		if (!$this->_initialized) {
257
			throw new TInvalidOperationException('memcache_not_initialized');
258
		} else {
259
			$this->_cache->setOptions(TPropertyValue::ensureArray($value));
260
		}
261
	}
262
263
	/**
264
	 * @return string persistent id for the instance of the memcache server
265
	 */
266
	public function getPersistentID()
267
	{
268
		return $this->_persistentid;
269
	}
270
271
	/**
272
	 * @param string $value persistent id for the instance of the memcache server
273
	 */
274
	public function setPersistentID($value)
275
	{
276
		$this->_persistentid = TPropertyValue::ensureString($value);
277
	}
278
279
	/**
280
	 * @param string $value if memcached instead memcache
281
	 * @throws TInvalidOperationException if the module is already initialized or usage of the old, unsupported memcache extension has been requested
282
	 * @deprecated since Prado 4.1, only memcached is available
283
	 */
284
	public function setUseMemcached($value)
285
	{
286
		if ($this->_initialized || $value === false) {
287
			throw new TInvalidOperationException('memcache_host_unchangeable');
288
		}
289
	}
290
291
	/**
292
	 * Retrieves a value from cache with a specified key.
293
	 * This is the implementation of the method declared in the parent class.
294
	 * @param string $key a unique key identifying the cached value
295
	 * @return string the value stored in cache, false if the value is not in the cache or expired.
296
	 */
297
	protected function getValue($key)
298
	{
299
		return $this->_cache->get($key);
300
	}
301
302
	/**
303
	 * Stores a value identified by a key in cache.
304
	 * This is the implementation of the method declared in the parent class.
305
	 *
306
	 * @param string $key the key identifying the value to be cached
307
	 * @param string $value the value to be cached
308
	 * @param int $expire the number of seconds in which the cached value will expire. 0 means never expire.
309
	 * @return bool true if the value is successfully stored into cache, false otherwise
310
	 */
311
	protected function setValue($key, $value, $expire)
312
	{
313
		return $this->_cache->set($key, $value, $expire);
314
	}
315
316
	/**
317
	 * Stores a value identified by a key into cache if the cache does not contain this key.
318
	 * This is the implementation of the method declared in the parent class.
319
	 *
320
	 * @param string $key the key identifying the value to be cached
321
	 * @param string $value the value to be cached
322
	 * @param int $expire the number of seconds in which the cached value will expire. 0 means never expire.
323
	 * @return bool true if the value is successfully stored into cache, false otherwise
324
	 */
325
	protected function addValue($key, $value, $expire)
326
	{
327
		$this->_cache->add($key, $value, $expire);
328
	}
329
330 4
	/**
331
	 * Deletes a value with the specified key from cache
332 4
	 * This is the implementation of the method declared in the parent class.
333
	 * @param string $key the key of the value to be deleted
334
	 * @return bool if no error happens during deletion
335
	 */
336
	protected function deleteValue($key)
337
	{
338
		return $this->_cache->delete($key);
339
	}
340
341
	/**
342
	 * Deletes all values from cache.
343
	 * Be careful of performing this operation if the cache is shared by multiple applications.
344 2
	 */
345
	public function flush()
346 2
	{
347
		return $this->_cache->flush();
348
	}
349
}
350