PageRenderTime 57ms CodeModel.GetById 20ms RepoModel.GetById 0ms app.codeStats 0ms

/modules/cache/classes/kohana/cache/memcache.php

https://github.com/purplexcite/Purpled-Blog-Engine
PHP | 268 lines | 74 code | 21 blank | 173 comment | 5 complexity | 03f8b8785bf0db3fb708fdf32523005b MD5 | raw file
Possible License(s): BSD-3-Clause
  1. <?php defined('SYSPATH') or die('No direct script access.');
  2. /**
  3. * [Kohana Cache](api/Kohana_Cache) Memcache driver,
  4. *
  5. * ### Supported cache engines
  6. *
  7. * * [Memcache](http://www.php.net/manual/en/book.memcache.php)
  8. * * [Memcached-tags](http://code.google.com/p/memcached-tags/)
  9. *
  10. * ### Configuration example
  11. *
  12. * Below is an example of a _memcache_ server configuration.
  13. *
  14. * return array(
  15. * 'default' => array( // Default group
  16. * 'driver' => 'memcache', // using Memcache driver
  17. * 'servers' => array( // Available server definitions
  18. * // First memcache server server
  19. * array(
  20. * 'host' => 'localhost',
  21. * 'port' => 11211,
  22. * 'persistent' => FALSE
  23. * 'weight' => 1,
  24. * 'timeout' => 1,
  25. * 'retry_interval' => 15,
  26. * 'status' => TRUE,
  27. * 'failure_callback' => array('className', 'classMethod')
  28. * ),
  29. * // Second memcache server
  30. * array(
  31. * 'host' => '192.168.1.5',
  32. * 'port' => 22122,
  33. * 'persistent' => TRUE
  34. * )
  35. * ),
  36. * 'compression' => FALSE, // Use compression?
  37. * ),
  38. * )
  39. *
  40. * In cases where only one cache group is required, if the group is named `default` there is
  41. * no need to pass the group name when instantiating a cache instance.
  42. *
  43. * #### General cache group configuration settings
  44. *
  45. * Below are the settings available to all types of cache driver.
  46. *
  47. * Name | Required | Description
  48. * -------------- | -------- | ---------------------------------------------------------------
  49. * driver | __YES__ | (_string_) The driver type to use
  50. * servers | __YES__ | (_array_) Associative array of server details, must include a __host__ key. (see _Memcache server configuration_ below)
  51. * compression | __NO__ | (_boolean_) Use data compression when caching
  52. *
  53. * #### Memcache server configuration
  54. *
  55. * The following settings should be used when defining each memcache server
  56. *
  57. * Name | Required | Description
  58. * ---------------- | -------- | ---------------------------------------------------------------
  59. * host | __YES__ | (_string_) The host of the memcache server, i.e. __localhost__; or __127.0.0.1__; or __memcache.domain.tld__
  60. * port | __NO__ | (_integer_) Point to the port where memcached is listening for connections. Set this parameter to 0 when using UNIX domain sockets. Default __11211__
  61. * persistent | __NO__ | (_boolean_) Controls the use of a persistent connection. Default __TRUE__
  62. * weight | __NO__ | (_integer_) Number of buckets to create for this server which in turn control its probability of it being selected. The probability is relative to the total weight of all servers. Default __1__
  63. * timeout | __NO__ | (_integer_) Value in seconds which will be used for connecting to the daemon. Think twice before changing the default value of 1 second - you can lose all the advantages of caching if your connection is too slow. Default __1__
  64. * retry_interval | __NO__ | (_integer_) Controls how often a failed server will be retried, the default value is 15 seconds. Setting this parameter to -1 disables automatic retry. Default __15__
  65. * status | __NO__ | (_boolean_) Controls if the server should be flagged as online. Default __TRUE__
  66. * failure_callback | __NO__ | (_[callback](http://www.php.net/manual/en/language.pseudo-types.php#language.types.callback)_) Allows the user to specify a callback function to run upon encountering an error. The callback is run before failover is attempted. The function takes two parameters, the hostname and port of the failed server. Default __NULL__
  67. *
  68. * ### System requirements
  69. *
  70. * * Kohana 3.0.x
  71. * * PHP 5.2.4 or greater
  72. * * Memcache (plus Memcached-tags for native tagging support)
  73. * * Zlib
  74. *
  75. * @package Kohana
  76. * @category Cache
  77. * @version 2.0
  78. * @author Kohana Team
  79. * @copyright (c) 2009-2010 Kohana Team
  80. * @license http://kohanaphp.com/license
  81. */
  82. class Kohana_Cache_Memcache extends Cache {
  83. // Memcache has a maximum cache lifetime of 30 days
  84. const CACHE_CEILING = 2592000;
  85. /**
  86. * Memcache resource
  87. *
  88. * @var Memcache
  89. */
  90. protected $_memcache;
  91. /**
  92. * Flags to use when storing values
  93. *
  94. * @var string
  95. */
  96. protected $_flags;
  97. /**
  98. * Constructs the memcache Kohana_Cache object
  99. *
  100. * @param array configuration
  101. * @throws Kohana_Cache_Exception
  102. */
  103. protected function __construct(array $config)
  104. {
  105. // Check for the memcache extention
  106. if ( ! extension_loaded('memcache'))
  107. {
  108. throw new Kohana_Cache_Exception('Memcache PHP extention not loaded');
  109. }
  110. parent::__construct($config);
  111. // Setup Memcache
  112. $this->_memcache = new Memcache;
  113. // Load servers from configuration
  114. $servers = Arr::get($this->_config, 'servers', NULL);
  115. if ( ! $servers)
  116. {
  117. // Throw an exception if no server found
  118. throw new Kohana_Cache_Exception('No Memcache servers defined in configuration');
  119. }
  120. // Setup default server configuration
  121. $config = array(
  122. 'host' => 'localhost',
  123. 'port' => 11211,
  124. 'persistent' => FALSE,
  125. 'weight' => 1,
  126. 'timeout' => 1,
  127. 'retry_interval' => 15,
  128. 'status' => TRUE,
  129. 'failure_callback' => NULL,
  130. );
  131. // Add the memcache servers to the pool
  132. foreach ($servers as $server)
  133. {
  134. // Merge the defined config with defaults
  135. $server += $config;
  136. if ( ! $this->_memcache->addServer($server['host'], $server['port'], $server['persistent'], $server['weight'], $server['timeout'], $server['retry_interval'], $server['status'], $server['failure_callback']))
  137. {
  138. throw new Kohana_Cache_Exception('Memcache could not connect to host \':host\' using port \':port\'', array(':host' => $server['host'], ':port' => $server['port']));
  139. }
  140. }
  141. // Setup the flags
  142. $this->_flags = Arr::get($this->_config, 'compression', FALSE) ? MEMCACHE_COMPRESSED : FALSE;
  143. }
  144. /**
  145. * Retrieve a cached value entry by id.
  146. *
  147. * // Retrieve cache entry from memcache group
  148. * $data = Cache::instance('memcache')->get('foo');
  149. *
  150. * // Retrieve cache entry from memcache group and return 'bar' if miss
  151. * $data = Cache::instance('memcache')->get('foo', 'bar');
  152. *
  153. * @param string id of cache to entry
  154. * @param string default value to return if cache miss
  155. * @return mixed
  156. * @throws Kohana_Cache_Exception
  157. */
  158. public function get($id, $default = NULL)
  159. {
  160. // Get the value from Memcache
  161. $value = $this->_memcache->get($this->_sanitize_id($id));
  162. // If the value wasn't found, normalise it
  163. if ($value === FALSE)
  164. {
  165. $value = (NULL === $default) ? NULL : $default;
  166. }
  167. // Return the value
  168. return $value;
  169. }
  170. /**
  171. * Set a value to cache with id and lifetime
  172. *
  173. * $data = 'bar';
  174. *
  175. * // Set 'bar' to 'foo' in memcache group for 10 minutes
  176. * if (Cache::instance('memcache')->set('foo', $data, 600))
  177. * {
  178. * // Cache was set successfully
  179. * return
  180. * }
  181. *
  182. * @param string id of cache entry
  183. * @param mixed data to set to cache
  184. * @param integer lifetime in seconds, maximum value 2592000
  185. * @return boolean
  186. */
  187. public function set($id, $data, $lifetime = 3600)
  188. {
  189. // If the lifetime is greater than the ceiling
  190. if ($lifetime > Cache_Memcache::CACHE_CEILING)
  191. {
  192. // Set the lifetime to maximum cache time
  193. $lifetime = Cache_Memcache::CACHE_CEILING + time();
  194. }
  195. // Else if the lifetime is greater than zero
  196. elseif ($lifetime > 0)
  197. {
  198. $lifetime += time();
  199. }
  200. // Else
  201. else
  202. {
  203. // Normalise the lifetime
  204. $lifetime = 0;
  205. }
  206. // Set the data to memcache
  207. return $this->_memcache->set($this->_sanitize_id($id), $data, $this->_flags, $lifetime);
  208. }
  209. /**
  210. * Delete a cache entry based on id
  211. *
  212. * // Delete the 'foo' cache entry immediately
  213. * Cache::instance('memcache')->delete('foo');
  214. *
  215. * // Delete the 'bar' cache entry after 30 seconds
  216. * Cache::instance('memcache')->delete('bar', 30);
  217. *
  218. * @param string id of entry to delete
  219. * @param integer timeout of entry, if zero item is deleted immediately, otherwise the item will delete after the specified value in seconds
  220. * @return boolean
  221. */
  222. public function delete($id, $timeout = 0)
  223. {
  224. // Delete the id
  225. return $this->_memcache->delete($this->_sanitize_id($id), $timeout);
  226. }
  227. /**
  228. * Delete all cache entries.
  229. *
  230. * Beware of using this method when
  231. * using shared memory cache systems, as it will wipe every
  232. * entry within the system for all clients.
  233. *
  234. * // Delete all cache entries in the default group
  235. * Cache::instance('memcache')->delete_all();
  236. *
  237. * @return boolean
  238. */
  239. public function delete_all()
  240. {
  241. $result = $this->_memcache->flush();
  242. // We must sleep after flushing, or overwriting will not work!
  243. // @see http://php.net/manual/en/function.memcache-flush.php#81420
  244. sleep(1);
  245. return $result;
  246. }
  247. }