MemcachedEngine.php 6.9 KB

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