MemcacheEngine.php 6.5 KB

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