MemCache.php 7.31 KB
Newer Older
Qiang Xue committed
1 2 3
<?php
/**
 * @link http://www.yiiframework.com/
Qiang Xue committed
4
 * @copyright Copyright (c) 2008 Yii Software LLC
Qiang Xue committed
5 6 7
 * @license http://www.yiiframework.com/license/
 */

Qiang Xue committed
8 9
namespace yii\caching;

Qiang Xue committed
10
use yii\base\Exception;
11
use yii\base\InvalidConfigException;
Qiang Xue committed
12

Qiang Xue committed
13
/**
Qiang Xue committed
14 15 16 17 18 19
 * MemCache implements a cache application component based on [memcache](http://pecl.php.net/package/memcache)
 * and [memcached](http://pecl.php.net/package/memcached).
 *
 * MemCache supports both [memcache](http://pecl.php.net/package/memcache) and
 * [memcached](http://pecl.php.net/package/memcached). By setting [[useMemcached]] to be true or false,
 * one can let MemCache to use either memcached or memcache, respectively.
Qiang Xue committed
20
 *
Qiang Xue committed
21 22
 * MemCache can be configured with a list of memcache servers by settings its [[servers]] property.
 * By default, MemCache assumes there is a memcache server running on localhost at port 11211.
Qiang Xue committed
23
 *
Qiang Xue committed
24
 * See [[Cache]] for common cache operations that ApcCache supports.
Qiang Xue committed
25 26 27 28
 *
 * Note, there is no security measure to protected data in memcache.
 * All data in memcache can be accessed by any process running in the system.
 *
29
 * To use MemCache as the cache application component, configure the application as follows,
Qiang Xue committed
30 31
 *
 * ~~~
Qiang Xue committed
32 33 34
 * array(
 *     'components'=>array(
 *         'cache'=>array(
35
 *             'class'=>'MemCache',
Qiang Xue committed
36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
 *             'servers'=>array(
 *                 array(
 *                     'host'=>'server1',
 *                     'port'=>11211,
 *                     'weight'=>60,
 *                 ),
 *                 array(
 *                     'host'=>'server2',
 *                     'port'=>11211,
 *                     'weight'=>40,
 *                 ),
 *             ),
 *         ),
 *     ),
 * )
Qiang Xue committed
51
 * ~~~
Qiang Xue committed
52
 *
Qiang Xue committed
53 54
 * In the above, two memcache servers are used: server1 and server2. You can configure more properties of
 * each server, such as `persistent`, `weight`, `timeout`. Please see [[MemCacheServer]] for available options.
Qiang Xue committed
55
 *
56
 * @property \Memcache|\Memcached $memCache The memcache instance (or memcached if [[useMemcached]] is true) used by this component.
Qiang Xue committed
57
 * @property MemCacheServer[] $servers List of memcache server configurations.
Qiang Xue committed
58 59
 *
 * @author Qiang Xue <qiang.xue@gmail.com>
Qiang Xue committed
60
 * @since 2.0
Qiang Xue committed
61
 */
62
class MemCache extends Cache
Qiang Xue committed
63 64 65
{
	/**
	 * @var boolean whether to use memcached or memcache as the underlying caching extension.
66 67
	 * If true, [memcached](http://pecl.php.net/package/memcached) will be used.
	 * If false, [memcache](http://pecl.php.net/package/memcache) will be used.
Qiang Xue committed
68 69
	 * Defaults to false.
	 */
70
	public $useMemcached = false;
Qiang Xue committed
71
	/**
Qiang Xue committed
72
	 * @var \Memcache|\Memcached the Memcache instance
Qiang Xue committed
73
	 */
74
	private $_cache = null;
Qiang Xue committed
75 76 77
	/**
	 * @var array list of memcache server configurations
	 */
78
	private $_servers = array();
Qiang Xue committed
79 80 81 82 83 84 85 86

	/**
	 * Initializes this application component.
	 * It creates the memcache instance and adds memcache servers.
	 */
	public function init()
	{
		parent::init();
87 88 89 90
		$servers = $this->getServers();
		$cache = $this->getMemCache();
		if (count($servers)) {
			foreach ($servers as $server) {
Qiang Xue committed
91 92 93
				if ($server->host === null) {
					throw new Exception("The 'host' property must be specified for every memcache server.");
				}
94 95 96
				if ($this->useMemcached) {
					$cache->addServer($server->host, $server->port, $server->weight);
				} else {
Qiang Xue committed
97 98
					$cache->addServer($server->host, $server->port, $server->persistent,
						$server->weight, $server->timeout, $server->retryInterval, $server->status);
99
				}
Qiang Xue committed
100
			}
101
		} else {
Qiang Xue committed
102
			$cache->addServer('127.0.0.1', 11211);
Qiang Xue committed
103 104 105 106
		}
	}

	/**
Qiang Xue committed
107 108
	 * Returns the underlying memcache (or memcached) object.
	 * @return \Memcache|\Memcached the memcache (or memcached) object used by this cache component.
Alexander Makarov committed
109
	 * @throws InvalidConfigException if memcache or memcached extension is not loaded
Qiang Xue committed
110
	 */
111
	public function getMemcache()
Qiang Xue committed
112
	{
Qiang Xue committed
113
		if ($this->_cache === null) {
114 115
			$extension = $this->useMemcached ? 'memcached' : 'memcache';
			if (!extension_loaded($extension)) {
116
				throw new InvalidConfigException("MemCache requires PHP $extension extension to be loaded.");
117
			}
Qiang Xue committed
118
			$this->_cache = $this->useMemcached ? new \Memcached : new \Memcache;
Qiang Xue committed
119
		}
Qiang Xue committed
120
		return $this->_cache;
Qiang Xue committed
121 122 123
	}

	/**
Qiang Xue committed
124 125
	 * Returns the memcache server configurations.
	 * @return MemCacheServer[] list of memcache server configurations.
Qiang Xue committed
126 127 128 129 130 131 132 133 134 135 136 137 138
	 */
	public function getServers()
	{
		return $this->_servers;
	}

	/**
	 * @param array $config list of memcache server configurations. Each element must be an array
	 * with the following keys: host, port, persistent, weight, timeout, retryInterval, status.
	 * @see http://www.php.net/manual/en/function.Memcache-addServer.php
	 */
	public function setServers($config)
	{
139
		foreach ($config as $c) {
Qiang Xue committed
140
			$this->_servers[] = new MemCacheServer($c);
141
		}
Qiang Xue committed
142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173
	}

	/**
	 * Retrieves a value from cache with a specified key.
	 * This is the implementation of the method declared in the parent class.
	 * @param string $key a unique key identifying the cached value
	 * @return string the value stored in cache, false if the value is not in the cache or expired.
	 */
	protected function getValue($key)
	{
		return $this->_cache->get($key);
	}

	/**
	 * Retrieves multiple values from cache with the specified keys.
	 * @param array $keys a list of keys identifying the cached values
	 * @return array a list of cached values indexed by the keys
	 */
	protected function getValues($keys)
	{
		return $this->useMemcached ? $this->_cache->getMulti($keys) : $this->_cache->get($keys);
	}

	/**
	 * Stores a value identified by a key in cache.
	 * This is the implementation of the method declared in the parent class.
	 *
	 * @param string $key the key identifying the value to be cached
	 * @param string $value the value to be cached
	 * @param integer $expire the number of seconds in which the cached value will expire. 0 means never expire.
	 * @return boolean true if the value is successfully stored into cache, false otherwise
	 */
174
	protected function setValue($key, $value, $expire)
Qiang Xue committed
175
	{
176 177 178 179 180
		if ($expire > 0) {
			$expire += time();
		} else {
			$expire = 0;
		}
Qiang Xue committed
181

182
		return $this->useMemcached ? $this->_cache->set($key, $value, $expire) : $this->_cache->set($key, $value, 0, $expire);
Qiang Xue committed
183 184 185 186 187 188 189 190 191 192 193
	}

	/**
	 * Stores a value identified by a key into cache if the cache does not contain this key.
	 * This is the implementation of the method declared in the parent class.
	 *
	 * @param string $key the key identifying the value to be cached
	 * @param string $value the value to be cached
	 * @param integer $expire the number of seconds in which the cached value will expire. 0 means never expire.
	 * @return boolean true if the value is successfully stored into cache, false otherwise
	 */
194
	protected function addValue($key, $value, $expire)
Qiang Xue committed
195
	{
196 197 198 199 200
		if ($expire > 0) {
			$expire += time();
		} else {
			$expire = 0;
		}
Qiang Xue committed
201

202
		return $this->useMemcached ? $this->_cache->add($key, $value, $expire) : $this->_cache->add($key, $value, 0, $expire);
Qiang Xue committed
203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225
	}

	/**
	 * Deletes a value with the specified key from cache
	 * This is the implementation of the method declared in the parent class.
	 * @param string $key the key of the value to be deleted
	 * @return boolean if no error happens during deletion
	 */
	protected function deleteValue($key)
	{
		return $this->_cache->delete($key, 0);
	}

	/**
	 * Deletes all values from cache.
	 * This is the implementation of the method declared in the parent class.
	 * @return boolean whether the flush operation was successful.
	 */
	protected function flushValues()
	{
		return $this->_cache->flush();
	}
}