Issues (1474)

framework/Caching/TMemCache.php (1 issue)

Severity
1
<?php
2
3
/**
4
 * TMemCache class file
5
 *
6
 * @author Qiang Xue <[email protected]>
7
 * @author Carl G. Mathisen <[email protected]>
8
 * @link https://github.com/pradosoft/prado
9
 * @license https://github.com/pradosoft/prado/blob/master/LICENSE
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 {@see 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 {@see init} is invoked.
29
 *
30
 * The following basic cache operations are implemented:
31
 * - {@see get} : retrieve the value with a key (if any) from cache
32
 * - {@see set} : store the value with a key into cache
33
 * - {@see add} : store the value only if cache does not have this key
34
 * - {@see delete} : delete the value with the specified key from cache
35
 * - {@see flush} : delete all values from cache
36
 *
37
 * Each value is associated with an expiration time. The {@see 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
 * ```php
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
 * ```
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
 * ```php
61
 * <module id="cache" class="Prado\Caching\TMemCache" Host="localhost" Port="11211" />
62
 * ```
63
 *
64
 * If you want a more complex configuration, you may use the method as follows.
65
 * ```php
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
 * ```
71
 *
72
 * If loaded, TMemCache will register itself with {@see \Prado\TApplication} as the
73
 * cache module. It can be accessed via {@see \Prado\TApplication::getCache()}.
74
 *
75
 * TMemCache may be configured in application configuration file as follows
76
 * ```php
77
 * <module id="cache" class="Prado\Caching\TMemCache" Host="localhost" Port="11211" />
78
 * ```
79
 * where {@see getHost Host} and {@see 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
 * {@see setPersistentID PersistentID}.
85
 * All instances created with the same persistent_id will share the same connection.
86
 *
87
 * @author Qiang Xue <[email protected]>
88
 * @since 3.0
89
 */
90
class TMemCache extends TCache
91
{
92
	/**
93
	 * @var bool if the module is initialized
94
	 */
95
	private $_initialized = false;
96
	/**
97
	 * @var \Memcached the Memcached instance
98
	 */
99
	private $_cache;
100
	/**
101
	 * @var string host name of the memcache server
102
	 */
103
	private $_host = 'localhost';
104
	/**
105
	 * @var int the port number of the memcache server
106
	 */
107
	private $_port = 11211;
108
	/**
109
	 * @var array list of servers available
110
	 */
111
	private $_servers = [];
112
	/**
113
	 * @var null|string persistent id for the instance of the memcache server
114
	 */
115
	private $_persistentid;
116
117
	/**
118
	 * Destructor.
119
	 * Disconnect the memcache server.
120
	 */
121
	public function __destruct()
122
	{
123
		if ($this->_cache !== null) {
124
			// Quit() is available only for memcached >= 2
125
			// $this->_cache->quit();
126
		}
127
		parent::__destruct();
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 \Prado\Xml\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
			Prado::trace('Skipping re-adding servers for persistent id ' . $this->_persistentid, TMemCache::class);
148
		} else {
149
			if (count($this->_servers)) {
150
				foreach ($this->_servers as $server) {
151 17
					Prado::trace('Adding server ' . $server['Host'] . ' from serverlist', TMemCache::class);
152 17
					if ($this->_cache->addServer(
153 17
						$server['Host'],
154
						$server['Port'],
155
						$server['Weight']
156
					) === false) {
157
						throw new TConfigurationException('memcache_connection_failed', $server['Host'], $server['Port']);
158
					}
159
				}
160
			} else {
161
				Prado::trace('Adding server ' . $this->_host, TMemCache::class);
162
				if ($this->_cache->addServer($this->_host, $this->_port) === false) {
163
					throw new TConfigurationException('memcache_connection_failed', $this->_host, $this->_port);
164
				}
165
			}
166
		}
167
		$this->_initialized = true;
168 17
		parent::init($config);
169 17
	}
170
171
	/**
172
	 * Loads configuration from an XML element
173 17
	 * @param \Prado\Xml\TXmlElement $xml configuration node
174
	 * @throws TConfigurationException if log route class or type is not specified
175
	 */
176 17
	private function loadConfig($xml)
177 17
	{
178 17
		if ($xml instanceof TXmlElement) {
0 ignored issues
show
$xml is always a sub-type of Prado\Xml\TXmlElement.
Loading history...
179
			foreach ($xml->getElementsByTagName('server') as $serverConfig) {
180
				$properties = $serverConfig->getAttributes();
181
				if (($host = $properties->remove('Host')) === null) {
182
					throw new TConfigurationException('memcache_serverhost_required');
183
				}
184
				if (($port = $properties->remove('Port')) === null) {
185 17
					throw new TConfigurationException('memcache_serverport_required');
186
				}
187 17
				if (!is_numeric($port)) {
188
					throw new TConfigurationException('memcache_serverport_invalid');
189
				}
190
				$server = ['Host' => $host, 'Port' => $port, 'Weight' => 1];
191
				$checks = [
192
					'Weight' => 'memcache_serverweight_invalid',
193
				];
194
				foreach ($checks as $property => $exception) {
195
					$value = $properties->remove($property);
196
					if ($value !== null && is_numeric($value)) {
197
						$server[$property] = $value;
198
					} elseif ($value !== null) {
199
						throw new TConfigurationException($exception);
200
					}
201
				}
202
				$this->_servers[] = $server;
203
			}
204
		}
205
	}
206
207
	/**
208
	 * @return string host name of the memcache server
209
	 */
210
	public function getHost()
211
	{
212
		return $this->_host;
213
	}
214
215
	/**
216
	 * @param string $value host name of the memcache server
217 17
	 * @throws TInvalidOperationException if the module is already initialized
218
	 */
219
	public function setHost($value)
220
	{
221
		if ($this->_initialized) {
222
			throw new TInvalidOperationException('memcache_host_unchangeable');
223
		} else {
224
			$this->_host = $value;
225
		}
226
	}
227
228
	/**
229
	 * @return int port number of the memcache server
230
	 */
231
	public function getPort()
232
	{
233
		return $this->_port;
234
	}
235
236
	/**
237
	 * @param int $value port number of the memcache server
238
	 * @throws TInvalidOperationException if the module is already initialized
239
	 */
240
	public function setPort($value)
241
	{
242
		if ($this->_initialized) {
243
			throw new TInvalidOperationException('memcache_port_unchangeable');
244
		} else {
245
			$this->_port = TPropertyValue::ensureInteger($value);
246
		}
247
	}
248
249
	/**
250
	 * @param array $value Set internal memcached options: https://www.php.net/manual/en/memcached.constants.php
251
	 * @throws TInvalidOperationException if the module is not initialized yet
252
	 */
253
	public function setOptions($value)
254
	{
255
		if (!$this->_initialized) {
256
			throw new TInvalidOperationException('memcache_not_initialized');
257
		} else {
258
			$this->_cache->setOptions(TPropertyValue::ensureArray($value));
259
		}
260
	}
261
262
	/**
263
	 * @return string persistent id for the instance of the memcache server
264
	 */
265
	public function getPersistentID()
266
	{
267
		return $this->_persistentid;
268
	}
269
270
	/**
271
	 * @param string $value persistent id for the instance of the memcache server
272
	 */
273
	public function setPersistentID($value)
274
	{
275
		$this->_persistentid = TPropertyValue::ensureString($value);
276
	}
277
278
	/**
279
	 * @param string $value if memcached instead memcache
280
	 * @throws TInvalidOperationException if the module is already initialized or usage of the old, unsupported memcache extension has been requested
281
	 * @deprecated since Prado 4.1, only memcached is available
282
	 */
283
	public function setUseMemcached($value)
284
	{
285
		if ($this->_initialized || TPropertyValue::ensureBoolean($value) === false) {
286
			throw new TInvalidOperationException('memcache_host_unchangeable');
287
		}
288
	}
289
290
	/**
291
	 * Retrieves a value from cache with a specified key.
292
	 * This is the implementation of the method declared in the parent class.
293
	 * @param string $key a unique key identifying the cached value
294
	 * @return false|string the value stored in cache, false if the value is not in the cache or expired.
295
	 */
296
	protected function getValue($key)
297
	{
298
		return $this->_cache->get($key);
299
	}
300
301
	/**
302
	 * Stores a value identified by a key in cache.
303
	 * This is the implementation of the method declared in the parent class.
304
	 *
305
	 * @param string $key the key identifying the value to be cached
306
	 * @param string $value the value to be cached
307
	 * @param int $expire the number of seconds in which the cached value will expire. 0 means never expire.
308
	 * @return bool true if the value is successfully stored into cache, false otherwise
309
	 */
310
	protected function setValue($key, $value, $expire)
311
	{
312
		return $this->_cache->set($key, $value, $expire);
313
	}
314
315
	/**
316
	 * Stores a value identified by a key into cache if the cache does not contain this key.
317
	 * This is the implementation of the method declared in the parent class.
318
	 *
319
	 * @param string $key the key identifying the value to be cached
320
	 * @param string $value the value to be cached
321
	 * @param int $expire the number of seconds in which the cached value will expire. 0 means never expire.
322
	 * @return bool true if the value is successfully stored into cache, false otherwise
323
	 */
324
	protected function addValue($key, $value, $expire)
325
	{
326
		return $this->_cache->add($key, $value, $expire);
327
	}
328
329
	/**
330 4
	 * Deletes a value with the specified key from cache
331
	 * This is the implementation of the method declared in the parent class.
332 4
	 * @param string $key the key of the value to be deleted
333
	 * @return bool if no error happens during deletion
334
	 */
335
	protected function deleteValue($key)
336
	{
337
		return $this->_cache->delete($key);
338
	}
339
340
	/**
341
	 * Deletes all values from cache.
342
	 * Be careful of performing this operation if the cache is shared by multiple applications.
343
	 * @return bool if no error happens during flush
344 2
	 */
345
	public function flush()
346 2
	{
347
		return $this->_cache->flush();
348
	}
349
}
350