363 lines
13KB

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