MemcachedEngine.php 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242
  1. <?php
  2. /**
  3. * Memcached storage engine for cache
  4. *
  5. * PHP 5
  6. *
  7. * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
  8. * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  9. *
  10. * Licensed under The MIT License
  11. * Redistributions of files must retain the above copyright notice.
  12. *
  13. * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  14. * @link http://cakephp.org CakePHP(tm) Project
  15. * @since CakePHP(tm) v 1.2.0.4933
  16. * @license http://opensource.org/licenses/mit-license.php MIT
  17. */
  18. /**
  19. * Memcached storage engine for cache. Memcached has some limitations in the amount of
  20. * control you have over expire times far in the future. See MemcachedEngine::write() for
  21. * more information.
  22. *
  23. * Cache::clear() is not implemented due to lack of support from memcached api.
  24. * If clear() support is primordial to you, use the default memcache engine.
  25. *
  26. * Main advantage of this Memcached engine over the Memcache engine is
  27. * support of binary protocol, and igbibnary serialization
  28. * (if memcached extension compiled with --enable-igbinary).
  29. * Compressed keys can also be incremented/decremented.
  30. *
  31. */
  32. class MemcachedEngine extends CacheEngine {
  33. /**
  34. * Memcached wrapper.
  35. *
  36. * @var Memcache
  37. */
  38. protected $_Memcached = null;
  39. /**
  40. * @var string
  41. */
  42. protected $_keys = '_keys';
  43. /**
  44. * @var string
  45. */
  46. protected $_keySeparator = '|';
  47. /**
  48. * Settings
  49. *
  50. * - servers = string or array of memcache servers, default => 127.0.0.1. If an
  51. * array MemcacheEngine will use them as a pool.
  52. * - compress = boolean, default => false
  53. *
  54. * @var array
  55. */
  56. public $settings = [];
  57. /**
  58. * Initialize the Cache Engine
  59. *
  60. * Called automatically by the cache frontend
  61. * To reinitialize the settings call Cache::engine('EngineName', [optional] settings = array());
  62. *
  63. * @param array $settings array of setting for the engine
  64. * @return bool True if the engine has been successfully initialized, false if not
  65. */
  66. public function init($settings = []) {
  67. if (!class_exists('Memcached')) {
  68. return false;
  69. }
  70. if (!isset($settings['prefix'])) {
  71. $settings['prefix'] = Inflector::slug(APP_DIR) . '_';
  72. }
  73. $settings += [
  74. 'engine' => 'Memcached',
  75. 'servers' => ['127.0.0.1'],
  76. 'compress' => false,
  77. 'persistent' => true
  78. ];
  79. parent::init($settings);
  80. $this->_keys .= $this->settings['prefix'];
  81. if (!is_array($this->settings['servers'])) {
  82. $this->settings['servers'] = [$this->settings['servers']];
  83. }
  84. if (!isset($this->_Memcached)) {
  85. $return = false;
  86. $this->_Memcached = new Memcached($this->settings['persistent'] ? 'mc' : null);
  87. $this->_setOptions();
  88. if (!count($this->_Memcached->getServerList())) {
  89. $servers = [];
  90. foreach ($this->settings['servers'] as $server) {
  91. $servers[] = $this->_parseServerString($server);
  92. }
  93. if ($this->_Memcached->addServers($servers)) {
  94. $return = true;
  95. }
  96. }
  97. if (!$this->_Memcached->get($this->_keys)) {
  98. $this->_Memcached->set($this->_keys, '');
  99. }
  100. return $return;
  101. }
  102. return true;
  103. }
  104. /**
  105. * Settings the memcached instance
  106. *
  107. */
  108. protected function _setOptions() {
  109. $this->_Memcached->setOption(Memcached::OPT_LIBKETAMA_COMPATIBLE, true);
  110. $this->_Memcached->setOption(Memcached::OPT_BINARY_PROTOCOL, true);
  111. if (Memcached::HAVE_IGBINARY) {
  112. $this->_Memcached->setOption(Memcached::OPT_SERIALIZER, Memcached::SERIALIZER_IGBINARY);
  113. }
  114. $this->_Memcached->setOption(Memcached::OPT_COMPRESSION, (bool)$this->settings['compress']);
  115. }
  116. /**
  117. * Parses the server address into the host/port. Handles both IPv6 and IPv4
  118. * addresses and Unix sockets
  119. *
  120. * @param string $server The server address string.
  121. * @return array Array containing host, port
  122. */
  123. protected function _parseServerString($server) {
  124. if ($server[0] === 'u') {
  125. return [$server, 0];
  126. }
  127. if (substr($server, 0, 1) === '[') {
  128. $position = strpos($server, ']:');
  129. if ($position !== false) {
  130. $position++;
  131. }
  132. } else {
  133. $position = strpos($server, ':');
  134. }
  135. $port = 11211;
  136. $host = $server;
  137. if ($position !== false) {
  138. $host = substr($server, 0, $position);
  139. $port = substr($server, $position + 1);
  140. }
  141. return [$host, (int)$port];
  142. }
  143. /**
  144. * Write data for key into cache. When using memcache as your cache engine
  145. * remember that the Memcache pecl extension does not support cache expiry times greater
  146. * than 30 days in the future. Any duration greater than 30 days will be treated as never expiring.
  147. *
  148. * @param string $key Identifier for the data
  149. * @param mixed $value Data to be cached
  150. * @param int $duration How long to cache the data, in seconds
  151. * @return bool True if the data was successfully cached, false on failure
  152. * @see http://php.net/manual/en/memcache.set.php
  153. */
  154. public function write($key, $value, $duration) {
  155. if ($duration > 30 * DAY) {
  156. $duration = 0;
  157. }
  158. $this->_Memcached->append($this->_keys, str_replace($this->settings['prefix'], '', $this->_keySeparator . $key));
  159. return $this->_Memcached->set($key, $value, $duration);
  160. }
  161. /**
  162. * Read a key from the cache
  163. *
  164. * @param string $key Identifier for the data
  165. * @return mixed The cached data, or false if the data doesn't exist, has expired, or if there was an error fetching it
  166. */
  167. public function read($key) {
  168. return $this->_Memcached->get($key);
  169. }
  170. /**
  171. * Increments the value of an integer cached key
  172. *
  173. * @param string $key Identifier for the data
  174. * @param int $offset How much to increment
  175. * @return New incremented value, false otherwise
  176. * @throws CacheException when you try to increment with compress = true
  177. */
  178. public function increment($key, $offset = 1) {
  179. return $this->_Memcached->increment($key, $offset);
  180. }
  181. /**
  182. * Decrements the value of an integer cached key
  183. *
  184. * @param string $key Identifier for the data
  185. * @param int $offset How much to subtract
  186. * @return New decremented value, false otherwise
  187. * @throws CacheException when you try to decrement with compress = true
  188. */
  189. public function decrement($key, $offset = 1) {
  190. return $this->_Memcached->decrement($key, $offset);
  191. }
  192. /**
  193. * Delete a key from the cache
  194. *
  195. * @param string $key Identifier for the data
  196. * @return bool True if the value was successfully deleted, false if it didn't exist or couldn't be removed
  197. */
  198. public function delete($key) {
  199. return $this->_Memcached->delete($key);
  200. }
  201. /**
  202. * Delete all keys from the cache
  203. *
  204. * @param bool $check
  205. * @return bool True if the cache was successfully cleared, false otherwise
  206. */
  207. public function clear($check) {
  208. $keys = array_slice(explode($this->_keySeparator, $this->_Memcached->get($this->_keys)), 1);
  209. foreach ($keys as $key) {
  210. $this->_Memcached->delete($this->settings['prefix'] . $key);
  211. }
  212. $this->_Memcached->delete($this->_keys);
  213. return true;
  214. }
  215. }