MemcacheEngine.php 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236
  1. <?php
  2. /**
  3. * Memcache storage engine for cache
  4. *
  5. *
  6. * PHP 5
  7. *
  8. * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
  9. * Copyright 2005-2011, 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 2005-2011, 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 MIT License (http://www.opensource.org/licenses/mit-license.php)
  19. */
  20. /**
  21. * Memcache storage engine for cache. Memcache has some limitations in the amount of
  22. * control you have over expire times far in the future. See MemcacheEngine::write() for
  23. * more information.
  24. *
  25. * @package Cake.Cache.Engine
  26. */
  27. class MemcacheEngine extends CacheEngine {
  28. /**
  29. * Memcache wrapper.
  30. *
  31. * @var Memcache
  32. * @access private
  33. */
  34. protected $_Memcache = null;
  35. /**
  36. * Settings
  37. *
  38. * - servers = string or array of memcache servers, default => 127.0.0.1. If an
  39. * array MemcacheEngine will use them as a pool.
  40. * - compress = boolean, default => false
  41. *
  42. * @var array
  43. * @access public
  44. */
  45. public $settings = array();
  46. /**
  47. * Initialize the Cache Engine
  48. *
  49. * Called automatically by the cache frontend
  50. * To reinitialize the settings call Cache::engine('EngineName', [optional] settings = array());
  51. *
  52. * @param array $settings array of setting for the engine
  53. * @return boolean True if the engine has been successfully initialized, false if not
  54. */
  55. public function init($settings = array()) {
  56. if (!class_exists('Memcache')) {
  57. return false;
  58. }
  59. parent::init(array_merge(array(
  60. 'engine'=> 'Memcache',
  61. 'prefix' => Inflector::slug(APP_DIR) . '_',
  62. 'servers' => array('127.0.0.1'),
  63. 'compress'=> false,
  64. 'persistent' => true
  65. ), $settings)
  66. );
  67. if ($this->settings['compress']) {
  68. $this->settings['compress'] = MEMCACHE_COMPRESSED;
  69. }
  70. if (!is_array($this->settings['servers'])) {
  71. $this->settings['servers'] = array($this->settings['servers']);
  72. }
  73. if (!isset($this->_Memcache)) {
  74. $return = false;
  75. $this->_Memcache = new Memcache();
  76. foreach ($this->settings['servers'] as $server) {
  77. list($host, $port) = $this->_parseServerString($server);
  78. if ($this->_Memcache->addServer($host, $port, $this->settings['persistent'])) {
  79. $return = true;
  80. }
  81. }
  82. return $return;
  83. }
  84. return true;
  85. }
  86. /**
  87. * Parses the server address into the host/port. Handles both IPv6 and IPv4
  88. * addresses
  89. *
  90. * @param string $server The server address string.
  91. * @return array Array containing host, port
  92. */
  93. function _parseServerString($server) {
  94. if (substr($server, 0, 1) == '[') {
  95. $position = strpos($server, ']:');
  96. if ($position !== false) {
  97. $position++;
  98. }
  99. } else {
  100. $position = strpos($server, ':');
  101. }
  102. $port = 11211;
  103. $host = $server;
  104. if ($position !== false) {
  105. $host = substr($server, 0, $position);
  106. $port = substr($server, $position + 1);
  107. }
  108. return array($host, $port);
  109. }
  110. /**
  111. * Write data for key into cache. When using memcache as your cache engine
  112. * remember that the Memcache pecl extension does not support cache expiry times greater
  113. * than 30 days in the future. Any duration greater than 30 days will be treated as never expiring.
  114. *
  115. * @param string $key Identifier for the data
  116. * @param mixed $value Data to be cached
  117. * @param integer $duration How long to cache the data, in seconds
  118. * @return boolean True if the data was successfully cached, false on failure
  119. * @see http://php.net/manual/en/memcache.set.php
  120. */
  121. public function write($key, $value, $duration) {
  122. if ($duration > 30 * DAY) {
  123. $duration = 0;
  124. }
  125. return $this->_Memcache->set($key, $value, $this->settings['compress'], $duration);
  126. }
  127. /**
  128. * Read a key from the cache
  129. *
  130. * @param string $key Identifier for the data
  131. * @return mixed The cached data, or false if the data doesn't exist, has expired, or if there was an error fetching it
  132. */
  133. public function read($key) {
  134. return $this->_Memcache->get($key);
  135. }
  136. /**
  137. * Increments the value of an integer cached key
  138. *
  139. * @param string $key Identifier for the data
  140. * @param integer $offset How much to increment
  141. * @return New incremented value, false otherwise
  142. * @throws CacheException when you try to increment with compress = true
  143. */
  144. public function increment($key, $offset = 1) {
  145. if ($this->settings['compress']) {
  146. throw new CacheException(
  147. __d('cake_dev', 'Method increment() not implemented for compressed cache in %s', __CLASS__)
  148. );
  149. }
  150. return $this->_Memcache->increment($key, $offset);
  151. }
  152. /**
  153. * Decrements the value of an integer cached key
  154. *
  155. * @param string $key Identifier for the data
  156. * @param integer $offset How much to subtract
  157. * @return New decremented value, false otherwise
  158. * @throws CacheException when you try to decrement with compress = true
  159. */
  160. public function decrement($key, $offset = 1) {
  161. if ($this->settings['compress']) {
  162. throw new CacheException(
  163. __d('cake_dev', 'Method decrement() not implemented for compressed cache in %s', __CLASS__)
  164. );
  165. }
  166. return $this->_Memcache->decrement($key, $offset);
  167. }
  168. /**
  169. * Delete a key from the cache
  170. *
  171. * @param string $key Identifier for the data
  172. * @return boolean True if the value was successfully deleted, false if it didn't exist or couldn't be removed
  173. */
  174. public function delete($key) {
  175. return $this->_Memcache->delete($key);
  176. }
  177. /**
  178. * Delete all keys from the cache
  179. *
  180. * @param boolean $check
  181. * @return boolean True if the cache was successfully cleared, false otherwise
  182. */
  183. public function clear($check) {
  184. if ($check) {
  185. return true;
  186. }
  187. foreach ($this->_Memcache->getExtendedStats('slabs') as $slabs) {
  188. foreach (array_keys($slabs) as $slabId) {
  189. if (!is_numeric($slabId)) {
  190. continue;
  191. }
  192. foreach ($this->_Memcache->getExtendedStats('cachedump', $slabId) as $stats) {
  193. if (!is_array($stats)) {
  194. continue;
  195. }
  196. foreach (array_keys($stats) as $key) {
  197. if (strpos($key, $this->settings['prefix']) === 0) {
  198. $this->_Memcache->delete($key);
  199. }
  200. }
  201. }
  202. }
  203. }
  204. return true;
  205. }
  206. /**
  207. * Connects to a server in connection pool
  208. *
  209. * @param string $host host ip address or name
  210. * @param integer $port Server port
  211. * @return boolean True if memcache server was connected
  212. */
  213. public function connect($host, $port = 11211) {
  214. if ($this->_Memcache->getServerStatus($host, $port) === 0) {
  215. if ($this->_Memcache->connect($host, $port)) {
  216. return true;
  217. }
  218. return false;
  219. }
  220. return true;
  221. }
  222. }