MemcachedEngine.php 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258
  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 2005-2012, 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-2012, 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. * Memcached storage engine for cache. This is the new more powerful memcache class (see MemcacheEngine for the former one).
  22. *
  23. * @package Cake.Cache.Engine
  24. */
  25. class MemcachedEngine extends CacheEngine {
  26. /**
  27. * Contains the compiled group names
  28. * (prefixed witht the global configuration prefix)
  29. *
  30. * @var array
  31. **/
  32. protected $_compiledGroupNames = array();
  33. /**
  34. * Memcache wrapper.
  35. *
  36. * @var Memcache
  37. */
  38. protected $_Memcached = null;
  39. /**
  40. * Settings
  41. *
  42. * - servers = string or array of memcache servers, default => 127.0.0.1. If an
  43. * array MemcacheEngine will use them as a pool.
  44. *
  45. * @var array
  46. */
  47. public $settings = array();
  48. /**
  49. * Initialize the Cache Engine
  50. *
  51. * Called automatically by the cache frontend
  52. * To reinitialize the settings call Cache::engine('EngineName', [optional] settings = array());
  53. *
  54. * @param array $settings array of setting for the engine
  55. * @return boolean True if the engine has been successfully initialized, false if not
  56. */
  57. public function init($settings = array()) {
  58. if (!class_exists('Memcached')) {
  59. return false;
  60. }
  61. if (!isset($settings['prefix'])) {
  62. $settings['prefix'] = Inflector::slug(APP_DIR) . '_';
  63. }
  64. $settings += array(
  65. 'engine' => 'Memcached',
  66. 'servers' => array('127.0.0.1'),
  67. 'compress' => false,
  68. 'persistent' => true
  69. );
  70. parent::init($settings);
  71. if (is_string($this->settings['servers'])) {
  72. $this->settings['servers'] = array($this->settings['servers']);
  73. }
  74. if (!isset($this->_Memcached)) {
  75. $return = false;
  76. $this->_Memcached = new Memcached();
  77. foreach ($this->settings['servers'] as $server) {
  78. list($host, $port) = $this->_parseServerString($server);
  79. if ($this->_Memcached->addServer($host, $port)) {
  80. $return = true;
  81. }
  82. }
  83. return $return;
  84. }
  85. return true;
  86. }
  87. /**
  88. * Parses the server address into the host/port. Handles both IPv6 and IPv4
  89. * addresses and Unix sockets
  90. *
  91. * @param string $server The server address string.
  92. * @return array Array containing host, port
  93. */
  94. protected function _parseServerString($server) {
  95. if ($server[0] == 'u') {
  96. return array($server, 0);
  97. }
  98. if (substr($server, 0, 1) == '[') {
  99. $position = strpos($server, ']:');
  100. if ($position !== false) {
  101. $position++;
  102. }
  103. } else {
  104. $position = strpos($server, ':');
  105. }
  106. $port = 11211;
  107. $host = $server;
  108. if ($position !== false) {
  109. $host = substr($server, 0, $position);
  110. $port = substr($server, $position + 1);
  111. }
  112. return array($host, $port);
  113. }
  114. /**
  115. * Write data for key into cache. When using memcache as your cache engine
  116. * remember that the Memcache pecl extension does not support cache expiry times greater
  117. * than 30 days in the future. Any duration greater than 30 days will be treated as never expiring.
  118. *
  119. * @param string $key Identifier for the data
  120. * @param mixed $value Data to be cached
  121. * @param integer $duration How long to cache the data, in seconds
  122. * @return boolean True if the data was successfully cached, false on failure
  123. * @see http://php.net/manual/en/memcache.set.php
  124. */
  125. public function write($key, $value, $duration) {
  126. if ($duration > 30 * DAY) {
  127. $duration = 0;
  128. }
  129. return $this->_Memcached->set($key, $value, $duration);
  130. }
  131. /**
  132. * Read a key from the cache
  133. *
  134. * @param string $key Identifier for the data
  135. * @return mixed The cached data, or false if the data doesn't exist, has expired, or if there was an error fetching it
  136. */
  137. public function read($key) {
  138. return $this->_Memcached->get($key);
  139. }
  140. /**
  141. * Increments the value of an integer cached key
  142. *
  143. * @param string $key Identifier for the data
  144. * @param integer $offset How much to increment
  145. * @return New incremented value, false otherwise
  146. * @throws CacheException when you try to increment with compress = true
  147. */
  148. public function increment($key, $offset = 1) {
  149. return $this->_Memcached->increment($key, $offset);
  150. }
  151. /**
  152. * Decrements the value of an integer cached key
  153. *
  154. * @param string $key Identifier for the data
  155. * @param integer $offset How much to subtract
  156. * @return New decremented value, false otherwise
  157. * @throws CacheException when you try to decrement with compress = true
  158. */
  159. public function decrement($key, $offset = 1) {
  160. return $this->_Memcached->decrement($key, $offset);
  161. }
  162. /**
  163. * Delete a key from the cache
  164. *
  165. * @param string $key Identifier for the data
  166. * @return boolean True if the value was successfully deleted, false if it didn't exist or couldn't be removed
  167. */
  168. public function delete($key) {
  169. return $this->_Memcached->delete($key);
  170. }
  171. /**
  172. * Delete all keys from the cache
  173. *
  174. * @param boolean $check
  175. * @return boolean True if the cache was successfully cleared, false otherwise
  176. */
  177. public function clear($check) {
  178. if ($check) {
  179. return true;
  180. }
  181. foreach ($this->_Memcached->getExtendedStats('slabs') as $slabs) {
  182. foreach (array_keys($slabs) as $slabId) {
  183. if (!is_numeric($slabId)) {
  184. continue;
  185. }
  186. foreach ($this->_Memcached->getExtendedStats('cachedump', $slabId) as $stats) {
  187. if (!is_array($stats)) {
  188. continue;
  189. }
  190. foreach (array_keys($stats) as $key) {
  191. if (strpos($key, $this->settings['prefix']) === 0) {
  192. $this->_Memcached->delete($key);
  193. }
  194. }
  195. }
  196. }
  197. }
  198. return true;
  199. }
  200. /**
  201. * Returns the `group value` for each of the configured groups
  202. * If the group initial value was not found, then it initializes
  203. * the group accordingly.
  204. *
  205. * @return array
  206. **/
  207. public function groups() {
  208. if (empty($this->_compiledGroupNames)) {
  209. foreach ($this->settings['groups'] as $group) {
  210. $this->_compiledGroupNames[] = $this->settings['prefix'] . $group;
  211. }
  212. }
  213. $groups = $this->_Memcached->get($this->_compiledGroupNames);
  214. if (count($groups) !== count($this->settings['groups'])) {
  215. foreach ($this->_compiledGroupNames as $group) {
  216. if (!isset($groups[$group])) {
  217. $this->_Memcached->set($group, 1, false, 0);
  218. $groups[$group] = 1;
  219. }
  220. }
  221. ksort($groups);
  222. }
  223. $result = array();
  224. $groups = array_values($groups);
  225. foreach ($this->settings['groups'] as $i => $group) {
  226. $result[] = $group . $groups[$i];
  227. }
  228. return $result;
  229. }
  230. /**
  231. * Increments the group value to simulate deletion of all keys under a group
  232. * old values will remain in storage until they expire.
  233. *
  234. * @return boolean success
  235. **/
  236. public function clearGroup($group) {
  237. return (bool)$this->_Memcached->increment($this->settings['prefix'] . $group);
  238. }
  239. }