PageRenderTime 52ms CodeModel.GetById 23ms RepoModel.GetById 0ms app.codeStats 0ms

/lib/Cake/Cache/Engine/MemcachedEngine.php

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