MemCache.php 11.7 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;

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

Qiang Xue committed
12
/**
Qiang Xue committed
13 14 15 16 17 18
 * 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
19
 *
Qiang Xue committed
20 21
 * 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
22
 *
23
 * See [[Cache]] for common cache operations that MemCache supports.
Qiang Xue committed
24 25 26 27
 *
 * 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.
 *
28
 * To use MemCache as the cache application component, configure the application as follows,
Qiang Xue committed
29 30
 *
 * ~~~
Alexander Makarov committed
31 32 33
 * [
 *     'components' => [
 *         'cache' => [
Qiang Xue committed
34
 *             'class' => 'yii\caching\MemCache',
Alexander Makarov committed
35 36
 *             'servers' => [
 *                 [
resurtm committed
37 38 39
 *                     'host' => 'server1',
 *                     'port' => 11211,
 *                     'weight' => 60,
Alexander Makarov committed
40 41
 *                 ],
 *                 [
resurtm committed
42 43 44
 *                     'host' => 'server2',
 *                     'port' => 11211,
 *                     'weight' => 40,
Alexander Makarov committed
45 46 47 48 49
 *                 ],
 *             ],
 *         ],
 *     ],
 * ]
Qiang Xue committed
50
 * ~~~
Qiang Xue committed
51
 *
Qiang Xue committed
52 53
 * 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
54
 *
55
 * @property \Memcache|\Memcached $memcache The memcache (or memcached) object used by this cache component.
56 57 58
 * This property is read-only.
 * @property MemCacheServer[] $servers List of memcache server configurations. Note that the type of this
 * property differs in getter and setter. See [[getServers()]] and [[setServers()]] for details.
Qiang Xue committed
59 60
 *
 * @author Qiang Xue <qiang.xue@gmail.com>
Qiang Xue committed
61
 * @since 2.0
Qiang Xue committed
62
 */
63
class MemCache extends Cache
Qiang Xue committed
64
{
65 66 67 68 69 70 71
    /**
     * @var boolean whether to use memcached or memcache as the underlying caching extension.
     * If true, [memcached](http://pecl.php.net/package/memcached) will be used.
     * If false, [memcache](http://pecl.php.net/package/memcache) will be used.
     * Defaults to false.
     */
    public $useMemcached = false;
72 73 74 75 76 77 78 79 80 81 82 83 84
    /**
     * @var string an ID that identifies a Memcached instance. This property is used only when [[useMemcached]] is true.
     * By default the Memcached instances are destroyed at the end of the request. To create an instance that
     * persists between requests, you may specify a unique ID for the instance. All instances created with the
     * same ID will share the same connection.
     * @see http://ca2.php.net/manual/en/memcached.construct.php
     */
    public $persistentId;
    /**
     * @var array options for Memcached. This property is used only when [[useMemcached]] is true.
     * @see http://ca2.php.net/manual/en/memcached.setoptions.php
     */
    public $options;
85

86 87 88 89 90 91 92 93
    /**
     * @var \Memcache|\Memcached the Memcache instance
     */
    private $_cache = null;
    /**
     * @var array list of memcache server configurations
     */
    private $_servers = [];
Qiang Xue committed
94

95

96 97 98 99 100 101 102
    /**
     * Initializes this application component.
     * It creates the memcache instance and adds memcache servers.
     */
    public function init()
    {
        parent::init();
103 104 105 106 107 108 109 110 111 112
        $this->addServers($this->getMemcache(), $this->getServers());
    }

    /**
     * @param \Memcache|\Memcached $cache
     * @param array $servers
     * @throws InvalidConfigException
     */
    protected function addServers($cache, $servers)
    {
113
        if (empty($servers)) {
114 115 116 117
            $servers = [new MemCacheServer([
                'host' => '127.0.0.1',
                'port' => 11211,
            ])];
118 119 120 121 122
        } else {
            foreach ($servers as $server) {
                if ($server->host === null) {
                    throw new InvalidConfigException("The 'host' property must be specified for every memcache server.");
                }
123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 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 174 175 176 177 178 179 180 181 182 183 184
            }
        }
        if ($this->useMemcached) {
            $this->addMemcachedServers($cache, $servers);
        } else {
            $this->addMemcacheServers($cache, $servers);
        }
    }

    /**
     * @param \Memcached $cache
     * @param array $servers
     */
    protected function addMemcachedServers($cache, $servers)
    {
        $existingServers = [];
        if ($this->persistentId !== null) {
            foreach ($cache->getServerList() as $s) {
                $existingServers[$s['host'] . ':' . $s['port']] = true;
            }
        }
        foreach ($servers as $server) {
            if (empty($existingServers) || !isset($existingServers[$server->host . ':' . $server->port])) {
                $cache->addServer($server->host, $server->port, $server->weight);
            }
        }
    }

    /**
     * @param \Memcache $cache
     * @param array $servers
     */
    protected function addMemcacheServers($cache, $servers)
    {
        $class = new \ReflectionClass($cache);
        $paramCount = $class->getMethod('addServer')->getNumberOfParameters();
        foreach ($servers as $server) {
            // $timeout is used for memcache versions that do not have $timeoutms parameter
            $timeout = (int) ($server->timeout / 1000) + (($server->timeout % 1000 > 0) ? 1 : 0);
            if ($paramCount === 9) {
                $cache->addServer(
                    $server->host,
                    $server->port,
                    $server->persistent,
                    $server->weight,
                    $timeout,
                    $server->retryInterval,
                    $server->status,
                    $server->failureCallback,
                    $server->timeout
                );
            } else {
                $cache->addServer(
                    $server->host,
                    $server->port,
                    $server->persistent,
                    $server->weight,
                    $timeout,
                    $server->retryInterval,
                    $server->status,
                    $server->failureCallback
                );
185 186 187
            }
        }
    }
Qiang Xue committed
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 193 194 195 196 197 198 199 200
     * @throws InvalidConfigException if memcache or memcached extension is not loaded
     */
    public function getMemcache()
    {
        if ($this->_cache === null) {
            $extension = $this->useMemcached ? 'memcached' : 'memcache';
            if (!extension_loaded($extension)) {
                throw new InvalidConfigException("MemCache requires PHP $extension extension to be loaded.");
            }
201 202 203 204 205 206 207 208 209

            if ($this->useMemcached) {
                $this->_cache = $this->persistentId !== null ? new \Memcached($this->persistentId) : new \Memcached;
                if (!empty($this->options)) {
                    $this->_cache->setOptions($this->options);
                }
            } else {
                $this->_cache = new \Memcache;
            }
210
        }
Qiang Xue committed
211

212 213
        return $this->_cache;
    }
Qiang Xue committed
214

215
    /**
216
     * Returns the memcache or memcached server configurations.
217 218 219 220 221 222
     * @return MemCacheServer[] list of memcache server configurations.
     */
    public function getServers()
    {
        return $this->_servers;
    }
Qiang Xue committed
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 228
     * @see http://php.net/manual/en/memcache.addserver.php
     * @see http://php.net/manual/en/memcached.addserver.php
229 230 231 232 233 234 235
     */
    public function setServers($config)
    {
        foreach ($config as $c) {
            $this->_servers[] = new MemCacheServer($c);
        }
    }
Qiang Xue committed
236

237 238 239
    /**
     * Retrieves a value from cache with a specified key.
     * This is the implementation of the method declared in the parent class.
240
     * @param string $key a unique key identifying the cached value
241 242 243 244 245 246
     * @return string|boolean 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);
    }
Qiang Xue committed
247

248 249
    /**
     * Retrieves multiple values from cache with the specified keys.
250
     * @param array $keys a list of keys identifying the cached values
251 252 253 254 255 256
     * @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);
    }
Qiang Xue committed
257

258 259 260 261
    /**
     * Stores a value identified by a key in cache.
     * This is the implementation of the method declared in the parent class.
     *
262 263 264
     * @param string $key the key identifying the value to be cached
     * @param string $value the value to be cached
     * @param integer $duration the number of seconds in which the cached value will expire. 0 means never expire.
265 266
     * @return boolean true if the value is successfully stored into cache, false otherwise
     */
Qiang Xue committed
267
    protected function setValue($key, $value, $duration)
268
    {
Qiang Xue committed
269
        $expire = $duration > 0 ? $duration + time() : 0;
270

271 272
        return $this->useMemcached ? $this->_cache->set($key, $value, $expire) : $this->_cache->set($key, $value, 0, $expire);
    }
273

274 275
    /**
     * Stores multiple key-value pairs in cache.
276 277 278
     * @param array $data array where key corresponds to cache key while value is the value stored
     * @param integer $duration the number of seconds in which the cached values will expire. 0 means never expire.
     * @return array array of failed keys. Always empty in case of using memcached.
279
     */
Qiang Xue committed
280
    protected function setValues($data, $duration)
281 282
    {
        if ($this->useMemcached) {
Qiang Xue committed
283
            $this->_cache->setMulti($data, $duration > 0 ? $duration + time() : 0);
284

285 286
            return [];
        } else {
Qiang Xue committed
287
            return parent::setValues($data, $duration);
288 289
        }
    }
Qiang Xue committed
290

291 292 293 294
    /**
     * 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.
     *
295 296 297
     * @param string $key the key identifying the value to be cached
     * @param string $value the value to be cached
     * @param integer $duration the number of seconds in which the cached value will expire. 0 means never expire.
298 299
     * @return boolean true if the value is successfully stored into cache, false otherwise
     */
Qiang Xue committed
300
    protected function addValue($key, $value, $duration)
301
    {
Qiang Xue committed
302
        $expire = $duration > 0 ? $duration + time() : 0;
303

304 305 306 307 308 309
        return $this->useMemcached ? $this->_cache->add($key, $value, $expire) : $this->_cache->add($key, $value, 0, $expire);
    }

    /**
     * Deletes a value with the specified key from cache
     * This is the implementation of the method declared in the parent class.
310
     * @param string $key the key of the value to be deleted
311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326
     * @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();
    }
Qiang Xue committed
327
}