MemcachedEngine.php 6.8 KB

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