MemcachedEngine.php 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239
  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://www.opensource.org/licenses/mit-license.php MIT License
  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 Keyname of the cache entry holding all the others key name
  41. */
  42. protected $_keys = '_keys';
  43. /**
  44. * @var string Token used to separe each keyname in the $_keys 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 = array();
  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 boolean True if the engine has been successfully initialized, false if not
  65. */
  66. public function init($settings = array()) {
  67. if (!class_exists('Memcached')) {
  68. return false;
  69. }
  70. if (!isset($settings['prefix'])) {
  71. $settings['prefix'] = Inflector::slug(APP_DIR) . '_';
  72. }
  73. $settings += array(
  74. 'engine' => 'Memcached',
  75. 'servers' => array('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'] = array($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 = array();
  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)) $this->_Memcached->set($this->_keys, '');
  98. return $return;
  99. }
  100. return true;
  101. }
  102. /**
  103. * Settings the memcached instance
  104. *
  105. */
  106. protected function _setOptions() {
  107. $this->_Memcached->setOption(Memcached::OPT_LIBKETAMA_COMPATIBLE, true);
  108. $this->_Memcached->setOption(Memcached::OPT_BINARY_PROTOCOL, true);
  109. if (Memcached::HAVE_IGBINARY) {
  110. $this->_Memcached->setOption(Memcached::OPT_SERIALIZER, Memcached::SERIALIZER_IGBINARY);
  111. }
  112. $this->_Memcached->setOption(Memcached::OPT_COMPRESSION, (bool)$this->settings['compress']);
  113. }
  114. /**
  115. * Parses the server address into the host/port. Handles both IPv6 and IPv4
  116. * addresses and Unix sockets
  117. *
  118. * @param string $server The server address string.
  119. * @return array Array containing host, port
  120. */
  121. protected function _parseServerString($server) {
  122. if ($server[0] === 'u') {
  123. return array($server, 0);
  124. }
  125. if (substr($server, 0, 1) === '[') {
  126. $position = strpos($server, ']:');
  127. if ($position !== false) {
  128. $position++;
  129. }
  130. } else {
  131. $position = strpos($server, ':');
  132. }
  133. $port = 11211;
  134. $host = $server;
  135. if ($position !== false) {
  136. $host = substr($server, 0, $position);
  137. $port = substr($server, $position + 1);
  138. }
  139. return array($host, (int)$port);
  140. }
  141. /**
  142. * Write data for key into cache. When using memcache as your cache engine
  143. * remember that the Memcache pecl extension does not support cache expiry times greater
  144. * than 30 days in the future. Any duration greater than 30 days will be treated as never expiring.
  145. *
  146. * @param string $key Identifier for the data
  147. * @param mixed $value Data to be cached
  148. * @param integer $duration How long to cache the data, in seconds
  149. * @return boolean True if the data was successfully cached, false on failure
  150. * @see http://php.net/manual/en/memcache.set.php
  151. */
  152. public function write($key, $value, $duration) {
  153. if ($duration > 30 * DAY) {
  154. $duration = 0;
  155. }
  156. $this->_Memcached->append($this->_keys, str_replace($this->settings['prefix'], '', $this->_keySeparator . $key));
  157. return $this->_Memcached->set($key, $value, $duration);
  158. }
  159. /**
  160. * Read a key from the cache
  161. *
  162. * @param string $key Identifier for the data
  163. * @return mixed The cached data, or false if the data doesn't exist, has expired, or if there was an error fetching it
  164. */
  165. public function read($key) {
  166. return $this->_Memcached->get($key);
  167. }
  168. /**
  169. * Increments the value of an integer cached key
  170. *
  171. * @param string $key Identifier for the data
  172. * @param integer $offset How much to increment
  173. * @return New incremented value, false otherwise
  174. * @throws CacheException when you try to increment with compress = true
  175. */
  176. public function increment($key, $offset = 1) {
  177. return $this->_Memcached->increment($key, $offset);
  178. }
  179. /**
  180. * Decrements the value of an integer cached key
  181. *
  182. * @param string $key Identifier for the data
  183. * @param integer $offset How much to subtract
  184. * @return New decremented value, false otherwise
  185. * @throws CacheException when you try to decrement with compress = true
  186. */
  187. public function decrement($key, $offset = 1) {
  188. return $this->_Memcached->decrement($key, $offset);
  189. }
  190. /**
  191. * Delete a key from the cache
  192. *
  193. * @param string $key Identifier for the data
  194. * @return boolean True if the value was successfully deleted, false if it didn't exist or couldn't be removed
  195. */
  196. public function delete($key) {
  197. return $this->_Memcached->delete($key);
  198. }
  199. /**
  200. * Delete all keys from the cache
  201. *
  202. * @param boolean $check
  203. * @return boolean True if the cache was successfully cleared, false otherwise
  204. */
  205. public function clear($check) {
  206. $keys = array_slice(explode($this->_keySeparator, $this->_Memcached->get($this->_keys)), 1);
  207. foreach ($keys as $key)
  208. $this->_Memcached->delete($this->settings['prefix'] . $key);
  209. $this->_Memcached->delete($this->_keys);
  210. return true;
  211. }
  212. }