PageRenderTime 34ms CodeModel.GetById 13ms RepoModel.GetById 1ms app.codeStats 0ms

/vendor/yiisoft/yii2/caching/MemCache.php

https://gitlab.com/aintenebris/memoria
PHP | 349 lines | 151 code | 24 blank | 174 comment | 20 complexity | 14adcedd6cd8310c9e7d06896ee50078 MD5 | raw file
  1. <?php
  2. /**
  3. * @link http://www.yiiframework.com/
  4. * @copyright Copyright (c) 2008 Yii Software LLC
  5. * @license http://www.yiiframework.com/license/
  6. */
  7. namespace yii\caching;
  8. use yii\base\InvalidConfigException;
  9. /**
  10. * MemCache implements a cache application component based on [memcache](http://pecl.php.net/package/memcache)
  11. * and [memcached](http://pecl.php.net/package/memcached).
  12. *
  13. * MemCache supports both [memcache](http://pecl.php.net/package/memcache) and
  14. * [memcached](http://pecl.php.net/package/memcached). By setting [[useMemcached]] to be true or false,
  15. * one can let MemCache to use either memcached or memcache, respectively.
  16. *
  17. * MemCache can be configured with a list of memcache servers by settings its [[servers]] property.
  18. * By default, MemCache assumes there is a memcache server running on localhost at port 11211.
  19. *
  20. * See [[Cache]] for common cache operations that MemCache supports.
  21. *
  22. * Note, there is no security measure to protected data in memcache.
  23. * All data in memcache can be accessed by any process running in the system.
  24. *
  25. * To use MemCache as the cache application component, configure the application as follows,
  26. *
  27. * ~~~
  28. * [
  29. * 'components' => [
  30. * 'cache' => [
  31. * 'class' => 'yii\caching\MemCache',
  32. * 'servers' => [
  33. * [
  34. * 'host' => 'server1',
  35. * 'port' => 11211,
  36. * 'weight' => 60,
  37. * ],
  38. * [
  39. * 'host' => 'server2',
  40. * 'port' => 11211,
  41. * 'weight' => 40,
  42. * ],
  43. * ],
  44. * ],
  45. * ],
  46. * ]
  47. * ~~~
  48. *
  49. * In the above, two memcache servers are used: server1 and server2. You can configure more properties of
  50. * each server, such as `persistent`, `weight`, `timeout`. Please see [[MemCacheServer]] for available options.
  51. *
  52. * @property \Memcache|\Memcached $memcache The memcache (or memcached) object used by this cache component.
  53. * This property is read-only.
  54. * @property MemCacheServer[] $servers List of memcache server configurations. Note that the type of this
  55. * property differs in getter and setter. See [[getServers()]] and [[setServers()]] for details.
  56. *
  57. * @author Qiang Xue <qiang.xue@gmail.com>
  58. * @since 2.0
  59. */
  60. class MemCache extends Cache
  61. {
  62. /**
  63. * @var boolean whether to use memcached or memcache as the underlying caching extension.
  64. * If true, [memcached](http://pecl.php.net/package/memcached) will be used.
  65. * If false, [memcache](http://pecl.php.net/package/memcache) will be used.
  66. * Defaults to false.
  67. */
  68. public $useMemcached = false;
  69. /**
  70. * @var string an ID that identifies a Memcached instance. This property is used only when [[useMemcached]] is true.
  71. * By default the Memcached instances are destroyed at the end of the request. To create an instance that
  72. * persists between requests, you may specify a unique ID for the instance. All instances created with the
  73. * same ID will share the same connection.
  74. * @see http://ca2.php.net/manual/en/memcached.construct.php
  75. */
  76. public $persistentId;
  77. /**
  78. * @var array options for Memcached. This property is used only when [[useMemcached]] is true.
  79. * @see http://ca2.php.net/manual/en/memcached.setoptions.php
  80. */
  81. public $options;
  82. /**
  83. * @var string memcached sasl username. This property is used only when [[useMemcached]] is true.
  84. * @see http://php.net/manual/en/memcached.setsaslauthdata.php
  85. */
  86. public $username;
  87. /**
  88. * @var string memcached sasl password. This property is used only when [[useMemcached]] is true.
  89. * @see http://php.net/manual/en/memcached.setsaslauthdata.php
  90. */
  91. public $password;
  92. /**
  93. * @var \Memcache|\Memcached the Memcache instance
  94. */
  95. private $_cache;
  96. /**
  97. * @var array list of memcache server configurations
  98. */
  99. private $_servers = [];
  100. /**
  101. * Initializes this application component.
  102. * It creates the memcache instance and adds memcache servers.
  103. */
  104. public function init()
  105. {
  106. parent::init();
  107. $this->addServers($this->getMemcache(), $this->getServers());
  108. }
  109. /**
  110. * Add servers to the server pool of the cache specified
  111. *
  112. * @param \Memcache|\Memcached $cache
  113. * @param MemCacheServer[] $servers
  114. * @throws InvalidConfigException
  115. */
  116. protected function addServers($cache, $servers)
  117. {
  118. if (empty($servers)) {
  119. $servers = [new MemCacheServer([
  120. 'host' => '127.0.0.1',
  121. 'port' => 11211,
  122. ])];
  123. } else {
  124. foreach ($servers as $server) {
  125. if ($server->host === null) {
  126. throw new InvalidConfigException("The 'host' property must be specified for every memcache server.");
  127. }
  128. }
  129. }
  130. if ($this->useMemcached) {
  131. $this->addMemcachedServers($cache, $servers);
  132. } else {
  133. $this->addMemcacheServers($cache, $servers);
  134. }
  135. }
  136. /**
  137. * Add servers to the server pool of the cache specified
  138. * Used for memcached PECL extension.
  139. *
  140. * @param \Memcached $cache
  141. * @param MemCacheServer[] $servers
  142. */
  143. protected function addMemcachedServers($cache, $servers)
  144. {
  145. $existingServers = [];
  146. if ($this->persistentId !== null) {
  147. foreach ($cache->getServerList() as $s) {
  148. $existingServers[$s['host'] . ':' . $s['port']] = true;
  149. }
  150. }
  151. foreach ($servers as $server) {
  152. if (empty($existingServers) || !isset($existingServers[$server->host . ':' . $server->port])) {
  153. $cache->addServer($server->host, $server->port, $server->weight);
  154. }
  155. }
  156. }
  157. /**
  158. * Add servers to the server pool of the cache specified
  159. * Used for memcache PECL extension.
  160. *
  161. * @param \Memcache $cache
  162. * @param MemCacheServer[] $servers
  163. */
  164. protected function addMemcacheServers($cache, $servers)
  165. {
  166. $class = new \ReflectionClass($cache);
  167. $paramCount = $class->getMethod('addServer')->getNumberOfParameters();
  168. foreach ($servers as $server) {
  169. // $timeout is used for memcache versions that do not have $timeoutms parameter
  170. $timeout = (int) ($server->timeout / 1000) + (($server->timeout % 1000 > 0) ? 1 : 0);
  171. if ($paramCount === 9) {
  172. $cache->addServer(
  173. $server->host,
  174. $server->port,
  175. $server->persistent,
  176. $server->weight,
  177. $timeout,
  178. $server->retryInterval,
  179. $server->status,
  180. $server->failureCallback,
  181. $server->timeout
  182. );
  183. } else {
  184. $cache->addServer(
  185. $server->host,
  186. $server->port,
  187. $server->persistent,
  188. $server->weight,
  189. $timeout,
  190. $server->retryInterval,
  191. $server->status,
  192. $server->failureCallback
  193. );
  194. }
  195. }
  196. }
  197. /**
  198. * Returns the underlying memcache (or memcached) object.
  199. * @return \Memcache|\Memcached the memcache (or memcached) object used by this cache component.
  200. * @throws InvalidConfigException if memcache or memcached extension is not loaded
  201. */
  202. public function getMemcache()
  203. {
  204. if ($this->_cache === null) {
  205. $extension = $this->useMemcached ? 'memcached' : 'memcache';
  206. if (!extension_loaded($extension)) {
  207. throw new InvalidConfigException("MemCache requires PHP $extension extension to be loaded.");
  208. }
  209. if ($this->useMemcached) {
  210. $this->_cache = $this->persistentId !== null ? new \Memcached($this->persistentId) : new \Memcached;
  211. if ($this->username !== null || $this->password !== null) {
  212. $this->_cache->setOption(\Memcached::OPT_BINARY_PROTOCOL, true);
  213. $this->_cache->setSaslAuthData($this->username, $this->password);
  214. }
  215. if (!empty($this->options)) {
  216. $this->_cache->setOptions($this->options);
  217. }
  218. } else {
  219. $this->_cache = new \Memcache;
  220. }
  221. }
  222. return $this->_cache;
  223. }
  224. /**
  225. * Returns the memcache or memcached server configurations.
  226. * @return MemCacheServer[] list of memcache server configurations.
  227. */
  228. public function getServers()
  229. {
  230. return $this->_servers;
  231. }
  232. /**
  233. * @param array $config list of memcache or memcached server configurations. Each element must be an array
  234. * with the following keys: host, port, persistent, weight, timeout, retryInterval, status.
  235. * @see http://php.net/manual/en/memcache.addserver.php
  236. * @see http://php.net/manual/en/memcached.addserver.php
  237. */
  238. public function setServers($config)
  239. {
  240. foreach ($config as $c) {
  241. $this->_servers[] = new MemCacheServer($c);
  242. }
  243. }
  244. /**
  245. * Retrieves a value from cache with a specified key.
  246. * This is the implementation of the method declared in the parent class.
  247. * @param string $key a unique key identifying the cached value
  248. * @return string|boolean the value stored in cache, false if the value is not in the cache or expired.
  249. */
  250. protected function getValue($key)
  251. {
  252. return $this->_cache->get($key);
  253. }
  254. /**
  255. * Retrieves multiple values from cache with the specified keys.
  256. * @param array $keys a list of keys identifying the cached values
  257. * @return array a list of cached values indexed by the keys
  258. */
  259. protected function getValues($keys)
  260. {
  261. return $this->useMemcached ? $this->_cache->getMulti($keys) : $this->_cache->get($keys);
  262. }
  263. /**
  264. * Stores a value identified by a key in cache.
  265. * This is the implementation of the method declared in the parent class.
  266. *
  267. * @param string $key the key identifying the value to be cached
  268. * @param string $value the value to be cached
  269. * @param integer $duration the number of seconds in which the cached value will expire. 0 means never expire.
  270. * @return boolean true if the value is successfully stored into cache, false otherwise
  271. */
  272. protected function setValue($key, $value, $duration)
  273. {
  274. $expire = $duration > 0 ? $duration + time() : 0;
  275. return $this->useMemcached ? $this->_cache->set($key, $value, $expire) : $this->_cache->set($key, $value, 0, $expire);
  276. }
  277. /**
  278. * Stores multiple key-value pairs in cache.
  279. * @param array $data array where key corresponds to cache key while value is the value stored
  280. * @param integer $duration the number of seconds in which the cached values will expire. 0 means never expire.
  281. * @return array array of failed keys. Always empty in case of using memcached.
  282. */
  283. protected function setValues($data, $duration)
  284. {
  285. if ($this->useMemcached) {
  286. $this->_cache->setMulti($data, $duration > 0 ? $duration + time() : 0);
  287. return [];
  288. } else {
  289. return parent::setValues($data, $duration);
  290. }
  291. }
  292. /**
  293. * Stores a value identified by a key into cache if the cache does not contain this key.
  294. * This is the implementation of the method declared in the parent class.
  295. *
  296. * @param string $key the key identifying the value to be cached
  297. * @param string $value the value to be cached
  298. * @param integer $duration the number of seconds in which the cached value will expire. 0 means never expire.
  299. * @return boolean true if the value is successfully stored into cache, false otherwise
  300. */
  301. protected function addValue($key, $value, $duration)
  302. {
  303. $expire = $duration > 0 ? $duration + time() : 0;
  304. return $this->useMemcached ? $this->_cache->add($key, $value, $expire) : $this->_cache->add($key, $value, 0, $expire);
  305. }
  306. /**
  307. * Deletes a value with the specified key from cache
  308. * This is the implementation of the method declared in the parent class.
  309. * @param string $key the key of the value to be deleted
  310. * @return boolean if no error happens during deletion
  311. */
  312. protected function deleteValue($key)
  313. {
  314. return $this->_cache->delete($key, 0);
  315. }
  316. /**
  317. * Deletes all values from cache.
  318. * This is the implementation of the method declared in the parent class.
  319. * @return boolean whether the flush operation was successful.
  320. */
  321. protected function flushValues()
  322. {
  323. return $this->_cache->flush();
  324. }
  325. }