4 * This file is part of the Symfony package.
6 * (c) Fabien Potencier <fabien@symfony.com>
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
12 namespace Symfony\Component\HttpFoundation\Session\Storage\Handler;
15 * Memcached based session storage handler based on the Memcached class
16 * provided by the PHP memcached extension.
18 * @see http://php.net/memcached
20 * @author Drak <drak@zikula.org>
22 class MemcachedSessionHandler extends AbstractSessionHandler
27 * @var int Time to live in seconds
32 * @var string Key prefix for shared environments
39 * List of available options:
40 * * prefix: The prefix to use for the memcached keys in order to avoid collision
41 * * expiretime: The time to live in seconds.
43 * @param \Memcached $memcached A \Memcached instance
44 * @param array $options An associative array of Memcached options
46 * @throws \InvalidArgumentException When unsupported options are passed
48 public function __construct(\Memcached $memcached, array $options = array())
50 $this->memcached = $memcached;
52 if ($diff = array_diff(array_keys($options), array('prefix', 'expiretime'))) {
53 throw new \InvalidArgumentException(sprintf('The following options are not supported "%s"', implode(', ', $diff)));
56 $this->ttl = isset($options['expiretime']) ? (int) $options['expiretime'] : 86400;
57 $this->prefix = isset($options['prefix']) ? $options['prefix'] : 'sf2s';
63 public function close()
71 protected function doRead($sessionId)
73 return $this->memcached->get($this->prefix.$sessionId) ?: '';
79 public function updateTimestamp($sessionId, $data)
81 $this->memcached->touch($this->prefix.$sessionId, time() + $this->ttl);
89 protected function doWrite($sessionId, $data)
91 return $this->memcached->set($this->prefix.$sessionId, $data, time() + $this->ttl);
97 protected function doDestroy($sessionId)
99 $result = $this->memcached->delete($this->prefix.$sessionId);
101 return $result || \Memcached::RES_NOTFOUND == $this->memcached->getResultCode();
107 public function gc($maxlifetime)
109 // not required here because memcached will auto expire the records anyhow.
114 * Return a Memcached instance.
118 protected function getMemcached()
120 return $this->memcached;