You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

342 lines
12KB

  1. <?php
  2. /**
  3. * @link http://www.yiiframework.com/
  4. * @copyright Copyright (c) 2008 Yii Software LLC
  5. * @license http://www.yiiframework.com/license/
  6. */
  7. namespace yii\caching;
  8. use yii\base\InvalidConfigException;
  9. /**
  10. * MemCache implements a cache application component based on [memcache](http://pecl.php.net/package/memcache)
  11. * and [memcached](http://pecl.php.net/package/memcached).
  12. *
  13. * MemCache supports both [memcache](http://pecl.php.net/package/memcache) and
  14. * [memcached](http://pecl.php.net/package/memcached). By setting [[useMemcached]] to be true or false,
  15. * one can let MemCache to use either memcached or memcache, respectively.
  16. *
  17. * MemCache can be configured with a list of memcache servers by settings its [[servers]] property.
  18. * By default, MemCache assumes there is a memcache server running on localhost at port 11211.
  19. *
  20. * See [[Cache]] for common cache operations that MemCache supports.
  21. *
  22. * Note, there is no security measure to protected data in memcache.
  23. * All data in memcache can be accessed by any process running in the system.
  24. *
  25. * To use MemCache as the cache application component, configure the application as follows,
  26. *
  27. * ~~~
  28. * [
  29. * 'components' => [
  30. * 'cache' => [
  31. * 'class' => 'yii\caching\MemCache',
  32. * 'servers' => [
  33. * [
  34. * 'host' => 'server1',
  35. * 'port' => 11211,
  36. * 'weight' => 60,
  37. * ],
  38. * [
  39. * 'host' => 'server2',
  40. * 'port' => 11211,
  41. * 'weight' => 40,
  42. * ],
  43. * ],
  44. * ],
  45. * ],
  46. * ]
  47. * ~~~
  48. *
  49. * In the above, two memcache servers are used: server1 and server2. You can configure more properties of
  50. * each server, such as `persistent`, `weight`, `timeout`. Please see [[MemCacheServer]] for available options.
  51. *
  52. * @property \Memcache|\Memcached $memcache The memcache (or memcached) object used by this cache component.
  53. * This property is read-only.
  54. * @property MemCacheServer[] $servers List of memcache server configurations. Note that the type of this
  55. * property differs in getter and setter. See [[getServers()]] and [[setServers()]] for details.
  56. *
  57. * @author Qiang Xue <qiang.xue@gmail.com>
  58. * @since 2.0
  59. */
  60. class MemCache extends Cache
  61. {
  62. /**
  63. * @var boolean whether to use memcached or memcache as the underlying caching extension.
  64. * If true, [memcached](http://pecl.php.net/package/memcached) will be used.
  65. * If false, [memcache](http://pecl.php.net/package/memcache) will be used.
  66. * Defaults to false.
  67. */
  68. public $useMemcached = false;
  69. /**
  70. * @var string an ID that identifies a Memcached instance. This property is used only when [[useMemcached]] is true.
  71. * By default the Memcached instances are destroyed at the end of the request. To create an instance that
  72. * persists between requests, you may specify a unique ID for the instance. All instances created with the
  73. * same ID will share the same connection.
  74. * @see http://ca2.php.net/manual/en/memcached.construct.php
  75. */
  76. public $persistentId;
  77. /**
  78. * @var array options for Memcached. This property is used only when [[useMemcached]] is true.
  79. * @see http://ca2.php.net/manual/en/memcached.setoptions.php
  80. */
  81. public $options;
  82. /**
  83. * @var string memcached sasl username. This property is used only when [[useMemcached]] is true.
  84. * @see http://php.net/manual/en/memcached.setsaslauthdata.php
  85. */
  86. public $username;
  87. /**
  88. * @var string memcached sasl password. This property is used only when [[useMemcached]] is true.
  89. * @see http://php.net/manual/en/memcached.setsaslauthdata.php
  90. */
  91. public $password;
  92. /**
  93. * @var \Memcache|\Memcached the Memcache instance
  94. */
  95. private $_cache = null;
  96. /**
  97. * @var array list of memcache server configurations
  98. */
  99. private $_servers = [];
  100. /**
  101. * Initializes this application component.
  102. * It creates the memcache instance and adds memcache servers.
  103. */
  104. public function init()
  105. {
  106. parent::init();
  107. $this->addServers($this->getMemcache(), $this->getServers());
  108. }
  109. /**
  110. * @param \Memcache|\Memcached $cache
  111. * @param array $servers
  112. * @throws InvalidConfigException
  113. */
  114. protected function addServers($cache, $servers)
  115. {
  116. if (empty($servers)) {
  117. $servers = [new MemCacheServer([
  118. 'host' => '127.0.0.1',
  119. 'port' => 11211,
  120. ])];
  121. } else {
  122. foreach ($servers as $server) {
  123. if ($server->host === null) {
  124. throw new InvalidConfigException("The 'host' property must be specified for every memcache server.");
  125. }
  126. }
  127. }
  128. if ($this->useMemcached) {
  129. $this->addMemcachedServers($cache, $servers);
  130. } else {
  131. $this->addMemcacheServers($cache, $servers);
  132. }
  133. }
  134. /**
  135. * @param \Memcached $cache
  136. * @param array $servers
  137. */
  138. protected function addMemcachedServers($cache, $servers)
  139. {
  140. $existingServers = [];
  141. if ($this->persistentId !== null) {
  142. foreach ($cache->getServerList() as $s) {
  143. $existingServers[$s['host'] . ':' . $s['port']] = true;
  144. }
  145. }
  146. foreach ($servers as $server) {
  147. if (empty($existingServers) || !isset($existingServers[$server->host . ':' . $server->port])) {
  148. $cache->addServer($server->host, $server->port, $server->weight);
  149. }
  150. }
  151. }
  152. /**
  153. * @param \Memcache $cache
  154. * @param array $servers
  155. */
  156. protected function addMemcacheServers($cache, $servers)
  157. {
  158. $class = new \ReflectionClass($cache);
  159. $paramCount = $class->getMethod('addServer')->getNumberOfParameters();
  160. foreach ($servers as $server) {
  161. // $timeout is used for memcache versions that do not have $timeoutms parameter
  162. $timeout = (int) ($server->timeout / 1000) + (($server->timeout % 1000 > 0) ? 1 : 0);
  163. if ($paramCount === 9) {
  164. $cache->addServer(
  165. $server->host,
  166. $server->port,
  167. $server->persistent,
  168. $server->weight,
  169. $timeout,
  170. $server->retryInterval,
  171. $server->status,
  172. $server->failureCallback,
  173. $server->timeout
  174. );
  175. } else {
  176. $cache->addServer(
  177. $server->host,
  178. $server->port,
  179. $server->persistent,
  180. $server->weight,
  181. $timeout,
  182. $server->retryInterval,
  183. $server->status,
  184. $server->failureCallback
  185. );
  186. }
  187. }
  188. }
  189. /**
  190. * Returns the underlying memcache (or memcached) object.
  191. * @return \Memcache|\Memcached the memcache (or memcached) object used by this cache component.
  192. * @throws InvalidConfigException if memcache or memcached extension is not loaded
  193. */
  194. public function getMemcache()
  195. {
  196. if ($this->_cache === null) {
  197. $extension = $this->useMemcached ? 'memcached' : 'memcache';
  198. if (!extension_loaded($extension)) {
  199. throw new InvalidConfigException("MemCache requires PHP $extension extension to be loaded.");
  200. }
  201. if ($this->useMemcached) {
  202. $this->_cache = $this->persistentId !== null ? new \Memcached($this->persistentId) : new \Memcached;
  203. if ($this->username !== null || $this->password !== null) {
  204. $this->_cache->setOption(\Memcached::OPT_BINARY_PROTOCOL, true);
  205. $this->_cache->setSaslAuthData($this->username, $this->password);
  206. }
  207. if (!empty($this->options)) {
  208. $this->_cache->setOptions($this->options);
  209. }
  210. } else {
  211. $this->_cache = new \Memcache;
  212. }
  213. }
  214. return $this->_cache;
  215. }
  216. /**
  217. * Returns the memcache or memcached server configurations.
  218. * @return MemCacheServer[] list of memcache server configurations.
  219. */
  220. public function getServers()
  221. {
  222. return $this->_servers;
  223. }
  224. /**
  225. * @param array $config list of memcache or memcached server configurations. Each element must be an array
  226. * with the following keys: host, port, persistent, weight, timeout, retryInterval, status.
  227. * @see http://php.net/manual/en/memcache.addserver.php
  228. * @see http://php.net/manual/en/memcached.addserver.php
  229. */
  230. public function setServers($config)
  231. {
  232. foreach ($config as $c) {
  233. $this->_servers[] = new MemCacheServer($c);
  234. }
  235. }
  236. /**
  237. * Retrieves a value from cache with a specified key.
  238. * This is the implementation of the method declared in the parent class.
  239. * @param string $key a unique key identifying the cached value
  240. * @return string|boolean the value stored in cache, false if the value is not in the cache or expired.
  241. */
  242. protected function getValue($key)
  243. {
  244. return $this->_cache->get($key);
  245. }
  246. /**
  247. * Retrieves multiple values from cache with the specified keys.
  248. * @param array $keys a list of keys identifying the cached values
  249. * @return array a list of cached values indexed by the keys
  250. */
  251. protected function getValues($keys)
  252. {
  253. return $this->useMemcached ? $this->_cache->getMulti($keys) : $this->_cache->get($keys);
  254. }
  255. /**
  256. * Stores a value identified by a key in cache.
  257. * This is the implementation of the method declared in the parent class.
  258. *
  259. * @param string $key the key identifying the value to be cached
  260. * @param string $value the value to be cached
  261. * @param integer $duration the number of seconds in which the cached value will expire. 0 means never expire.
  262. * @return boolean true if the value is successfully stored into cache, false otherwise
  263. */
  264. protected function setValue($key, $value, $duration)
  265. {
  266. $expire = $duration > 0 ? $duration + time() : 0;
  267. return $this->useMemcached ? $this->_cache->set($key, $value, $expire) : $this->_cache->set($key, $value, 0, $expire);
  268. }
  269. /**
  270. * Stores multiple key-value pairs in cache.
  271. * @param array $data array where key corresponds to cache key while value is the value stored
  272. * @param integer $duration the number of seconds in which the cached values will expire. 0 means never expire.
  273. * @return array array of failed keys. Always empty in case of using memcached.
  274. */
  275. protected function setValues($data, $duration)
  276. {
  277. if ($this->useMemcached) {
  278. $this->_cache->setMulti($data, $duration > 0 ? $duration + time() : 0);
  279. return [];
  280. } else {
  281. return parent::setValues($data, $duration);
  282. }
  283. }
  284. /**
  285. * Stores a value identified by a key into cache if the cache does not contain this key.
  286. * This is the implementation of the method declared in the parent class.
  287. *
  288. * @param string $key the key identifying the value to be cached
  289. * @param string $value the value to be cached
  290. * @param integer $duration the number of seconds in which the cached value will expire. 0 means never expire.
  291. * @return boolean true if the value is successfully stored into cache, false otherwise
  292. */
  293. protected function addValue($key, $value, $duration)
  294. {
  295. $expire = $duration > 0 ? $duration + time() : 0;
  296. return $this->useMemcached ? $this->_cache->add($key, $value, $expire) : $this->_cache->add($key, $value, 0, $expire);
  297. }
  298. /**
  299. * Deletes a value with the specified key from cache
  300. * This is the implementation of the method declared in the parent class.
  301. * @param string $key the key of the value to be deleted
  302. * @return boolean if no error happens during deletion
  303. */
  304. protected function deleteValue($key)
  305. {
  306. return $this->_cache->delete($key, 0);
  307. }
  308. /**
  309. * Deletes all values from cache.
  310. * This is the implementation of the method declared in the parent class.
  311. * @return boolean whether the flush operation was successful.
  312. */
  313. protected function flushValues()
  314. {
  315. return $this->_cache->flush();
  316. }
  317. }