Ejemplo n.º 1
0
 /**
  * update
  *
  * @param mixed  $identifier identifier to save
  * @param string $amount     the current amount
  * @param string $timespan   the timespan in seconds
  *
  * @return boolean
  */
 public function update($identifier = null, $amount = null, $timespan = null)
 {
     if (!$identifier && !$amount && !$timespan) {
         throw new \InvalidArgumentException('identifier, amount and timespan are required');
     }
     return $this->memcached->replace($this->fileName($identifier), $amount, $timespan);
 }
Ejemplo n.º 2
0
 /**
  * 替换已经存在的key
  * @param $key
  * @param $val
  * @param $expireTime
  * @return bool
  */
 public function update($key, $val, $expireTime)
 {
     $ret = $this->dbh->replace($key, $val, $expireTime);
     if ($ret === false) {
         $this->error('update', $key);
     }
     return true;
 }
Ejemplo n.º 3
0
 function replace($key, $value, $ttl = 0)
 {
     $key = str_replace('\\', '/', $key);
     if (!$this->memcached->replace($key, $value, $ttl)) {
         $message = sprintf('Memcache::replace() with key "%s" failed', $key);
         \ManiaLib\Utils\Logger::error($message);
     }
 }
Ejemplo n.º 4
0
 /**
  * {@inheritdoc}
  */
 public function put($key, $data, $ttl = 0)
 {
     if ($ttl !== 0) {
         $ttl += time();
     }
     if ($this->memcached->replace($key, $data, $ttl) === false) {
         return $this->memcached->set($key, $data, $ttl);
     }
     return true;
 }
Ejemplo n.º 5
0
	/**
	 * Unlock cached item - override parent for cacheid compatibility with lock
	 *
	 * @param   string  $id     The cache data id
	 * @param   string  $group  The cache data group
	 *
	 * @return  boolean  True on success, false otherwise.
	 *
	 * @since   12.1
	 */
	public function unlock($id, $group = null)
	{
		$cache_id = $this->_getCacheId($id, $group) . '_lock';

		if (!$this->lockindex())
		{
			return false;
		}

		$index = self::$_db->get($this->_hash . '-index');

		if ($index === false)
		{
			$index = array();
		}

		foreach ($index as $key => $value)
		{
			if ($value->name == $cache_id)
			{
				unset($index[$key]);
			}
			break;
		}

		self::$_db->replace($this->_hash . '-index', $index, 0);
		$this->unlockindex();

		return self::$_db->delete($cache_id);
	}
 /**
  * Replaces a value in cache.
  *
  * This method is similar to "add"; however, is does not successfully set a value if
  * the object's key is not already set in cache.
  *
  * @link    http://www.php.net/manual/en/memcached.replace.php
  *
  * @param   string      $key            The key under which to store the value.
  * @param   mixed       $value          The value to store.
  * @param   string      $group          The group value appended to the $key.
  * @param   int         $expiration     The expiration time, defaults to 0.
  * @param   string      $server_key     The key identifying the server to store the value on.
  * @param   bool        $byKey          True to store in internal cache by key; false to not store by key
  * @return  bool                        Returns TRUE on success or FALSE on failure.
  */
 public function replace($key, $value, $group = 'default', $expiration = 0, $server_key = '', $byKey = false)
 {
     $derived_key = $this->buildKey($key, $group);
     $expiration = $this->sanitize_expiration($expiration);
     // If group is a non-Memcached group, save to runtime cache, not Memcached
     if (in_array($group, $this->no_mc_groups)) {
         // Replace won't save unless the key already exists; mimic this behavior here
         if (!isset($this->cache[$derived_key])) {
             return false;
         }
         $this->cache[$derived_key] = $value;
         return true;
     }
     // Save to Memcached
     if (false !== $byKey) {
         $result = $this->mc->replaceByKey($server_key, $derived_key, $value, $expiration);
     } else {
         $result = $this->mc->replace($derived_key, $value, $expiration);
     }
     // Store in runtime cache if add was successful
     if (Memcached::RES_SUCCESS === $this->getResultCode()) {
         $this->add_to_internal_cache($derived_key, $value);
     }
     return $result;
 }
 /**
  * Get lock
  *
  * Acquires an (emulated) lock.
  *
  * @param	string	$session_id	Session ID
  * @return	bool
  */
 protected function _get_lock($session_id)
 {
     if (isset($this->_lock_key)) {
         return $this->_memcached->replace($this->_lock_key, time(), 300);
     }
     // 30 attempts to obtain a lock, in case another request already has it
     $lock_key = $this->_key_prefix . $session_id . ':lock';
     $attempt = 0;
     do {
         if ($this->_memcached->get($lock_key)) {
             sleep(1);
             continue;
         }
         if (!$this->_memcached->set($lock_key, time(), 300)) {
             return FALSE;
         }
         $this->_lock_key = $lock_key;
         break;
     } while (++$attempt < 30);
     if ($attempt === 30) {
         return FALSE;
     }
     $this->_lock = TRUE;
     return TRUE;
 }
Ejemplo n.º 8
0
 /**
  * Get lock
  *
  * Acquires an (emulated) lock.
  *
  * @param    string $session_id Session ID
  *
  * @return    bool
  */
 protected function lockSession(string $session_id) : bool
 {
     if (isset($this->lockKey)) {
         return $this->memcached->replace($this->lockKey, time(), 300);
     }
     // 30 attempts to obtain a lock, in case another request already has it
     $lock_key = $this->keyPrefix . $session_id . ':lock';
     $attempt = 0;
     do {
         if ($this->memcached->get($lock_key)) {
             sleep(1);
             continue;
         }
         if (!$this->memcached->set($lock_key, time(), 300)) {
             $this->logger->error('Session: Error while trying to obtain lock for ' . $this->keyPrefix . $session_id);
             return false;
         }
         $this->lockKey = $lock_key;
         break;
     } while (++$attempt < 30);
     if ($attempt === 30) {
         $this->logger->error('Session: Unable to obtain lock for ' . $this->keyPrefix . $session_id . ' after 30 attempts, aborting.');
         return false;
     }
     $this->lock = true;
     return true;
 }
Ejemplo n.º 9
0
 /**
  * Replace an item.
  *
  * Options:
  *  - ttl <float> optional
  *    - The time-to-live (Default: ttl of object)
  *  - namespace <string> optional
  *    - The namespace to use (Default: namespace of object)
  *
  * @param  string $key
  * @param  mixed  $value
  * @param  array  $options
  * @return boolean
  * @throws Exception
  *
  * @triggers replaceItem.pre(PreEvent)
  * @triggers replaceItem.post(PostEvent)
  * @triggers replaceItem.exception(ExceptionEvent)
  */
 public function replaceItem($key, $value, array $options = array())
 {
     $baseOptions = $this->getOptions();
     if (!$baseOptions->getWritable()) {
         return false;
     }
     $this->normalizeOptions($options);
     $this->normalizeKey($key);
     $args = new ArrayObject(array('key' => &$key, 'value' => &$value, 'options' => &$options));
     try {
         $eventRs = $this->triggerPre(__FUNCTION__, $args);
         if ($eventRs->stopped()) {
             return $eventRs->last();
         }
         $this->memcached->setOption(MemcachedResource::OPT_PREFIX_KEY, $options['namespace']);
         $expiration = $this->expirationTime($options['ttl']);
         if (!$this->memcached->replace($key, $value, $expiration)) {
             throw $this->getExceptionByResultCode($this->memcached->getResultCode());
         }
         $result = true;
         return $this->triggerPost(__FUNCTION__, $args, $result);
     } catch (\Exception $e) {
         return $this->triggerException(__FUNCTION__, $args, $e);
     }
 }
 /**
  * Get lock
  *
  * Acquires an (emulated) lock.
  *
  * @param	string	$session_id	Session ID
  * @return	bool
  */
 protected function _get_lock($session_id)
 {
     // PHP 7 reuses the SessionHandler object on regeneration,
     // so we need to check here if the lock key is for the
     // correct session ID.
     if ($this->_lock_key === $this->_key_prefix . $session_id . ':lock') {
         return $this->_memcached->replace($this->_lock_key, time(), 300) ? $this->_success : $this->_failure;
     }
     // 30 attempts to obtain a lock, in case another request already has it
     $lock_key = $this->_key_prefix . $session_id . ':lock';
     $attempt = 0;
     do {
         if ($this->_memcached->get($lock_key)) {
             sleep(1);
             continue;
         }
         if (!$this->_memcached->set($lock_key, time(), 300)) {
             log_message('error', 'Session: Error while trying to obtain lock for ' . $this->_key_prefix . $session_id);
             return $this->_failure;
         }
         $this->_lock_key = $lock_key;
         break;
     } while (++$attempt < 30);
     if ($attempt === 30) {
         log_message('error', 'Session: Unable to obtain lock for ' . $this->_key_prefix . $session_id . ' after 30 attempts, aborting.');
         return $this->_failure;
     }
     $this->_lock = TRUE;
     return $this->_success;
 }
Ejemplo n.º 11
0
 /**
  * @Name replace
  *
  * @param string|array $key 要替换的key
  * @param mixed $value 要替换的value
  * @param int|null $expiration 到期时间
  * @return bool add by cheng.yafei
  *
  */
 public function replace($key = NULL, $value = NULL, $expiration = NULL)
 {
     if (is_null($expiration)) {
         $expiration = C(Config::MEMCACHE_EXPIRATION);
     }
     if (is_array($key)) {
         foreach ($key as $multi) {
             if (!isset($multi['expiration']) || $multi['expiration'] == '') {
                 $multi['expiration'] = $expiration;
             }
             $this->replace($multi['key'], $multi['value'], $multi['expiration']);
         }
         $replace_status = true;
     } else {
         $this->local_cache[$this->key_name($key)] = $value;
         $replace_status = false;
         switch ($this->client_type) {
             case 'Memcache':
                 $replace_status = $this->m->replace($this->key_name($key), $value, C(Config::MEMCACHE_COMPRESSION), $expiration);
                 break;
             case 'Memcached':
                 $replace_status = $this->m->replace($this->key_name($key), $value, $expiration);
                 break;
         }
     }
     return $replace_status;
 }
Ejemplo n.º 12
0
 /**
  * Get lock
  *
  * Acquires an (emulated) lock.
  *
  * @param    string $session_id Session ID
  * @return    bool
  */
 protected function _get_lock($session_id)
 {
     if (isset($this->_lock_key)) {
         return $this->_memcached->replace($this->_lock_key, time(), 300);
     }
     // 30 attempts to obtain a lock, in case another request already has it
     $lock_key = $this->_key_prefix . $session_id . ':lock';
     $attempt = 0;
     do {
         if ($this->_memcached->get($lock_key)) {
             sleep(1);
             continue;
         }
         if (!$this->_memcached->set($lock_key, time(), 300)) {
             log_message('error', 'Session: Error while trying to obtain lock for ' . $this->_key_prefix . $session_id);
             return FALSE;
         }
         $this->_lock_key = $lock_key;
         break;
     } while (++$attempt < 30);
     if ($attempt === 30) {
         log_message('error', 'Session: Unable to obtain lock for ' . $this->_key_prefix . $session_id . ' after 30 attempts, aborting.');
         return FALSE;
     }
     $this->_lock = TRUE;
     return TRUE;
 }
 /**
  * Write
  *
  * Writes (create / update) session data
  *
  * @param	string	$session_id	Session ID
  * @param	string	$session_data	Serialized session data
  * @return	bool
  */
 public function write($session_id, $session_data)
 {
     if (!isset($this->_memcached)) {
         return $this->_fail();
     } elseif ($session_id !== $this->_session_id) {
         if (!$this->_release_lock() or !$this->_get_lock($session_id)) {
             return $this->_fail();
         }
         $this->_fingerprint = md5('');
         $this->_session_id = $session_id;
     }
     if (isset($this->_lock_key)) {
         $key = $this->_key_prefix . $session_id;
         $this->_memcached->replace($this->_lock_key, time(), 300);
         if ($this->_fingerprint !== ($fingerprint = md5($session_data))) {
             if ($this->_memcached->replace($key, $session_data, $this->_config['expiration']) or $this->_memcached->getResultCode() === Memcached::RES_NOTFOUND && $this->_memcached->set($key, $session_data, $this->_config['expiration'])) {
                 $this->_fingerprint = $fingerprint;
                 return $this->_success;
             }
             return $this->_fail();
         }
         if ($this->_memcached->touch($key, $this->_config['expiration']) or $this->_memcached->getResultCode() === Memcached::RES_NOTFOUND && $this->_memcached->set($key, $session_data, $this->_config['expiration'])) {
             return $this->_success;
         }
     }
     return $this->_fail();
 }
Ejemplo n.º 14
0
 /**
  * Replace an item.
  *
  * Options:
  *  - namespace <string> optional
  *    - The namespace to use (Default: namespace of object)
  *  - tags <array> optional
  *    - An array of tags
  *
  * @param  string $key
  * @param  mixed  $value
  * @param  array  $options
  * @return boolean
  * @throws Exception
  *
  * @triggers replaceItem.pre(PreEvent)
  * @triggers replaceItem.post(PostEvent)
  * @triggers replaceItem.exception(ExceptionEvent)
  */
 public function replaceItem($key, $value, array $options = array())
 {
     $baseOptions = $this->getOptions();
     if (!$baseOptions->getWritable()) {
         return false;
     }
     $this->normalizeOptions($options);
     $this->normalizeKey($key);
     $args = new ArrayObject(array('key' => &$key, 'value' => &$value, 'options' => &$options));
     try {
         $eventRs = $this->triggerPre(__FUNCTION__, $args);
         if ($eventRs->stopped()) {
             return $eventRs->last();
         }
         $internalKey = $options['namespace'] . $baseOptions->getNamespaceSeparator() . $key;
         if (!$this->memcached->get($internalKey)) {
             throw new Exception\ItemNotFoundException("Key '{$internalKey}' doesn't exist");
         }
         $result = $this->memcached->replace($internalKey, $value, $options['ttl']);
         if ($result === false) {
             $type = is_object($value) ? get_class($value) : gettype($value);
             throw new Exception\RuntimeException("Memcached::replace('{$internalKey}', <{$type}>, {$options['ttl']}) failed");
         }
         return $this->triggerPost(__FUNCTION__, $args, $result);
     } catch (\Exception $e) {
         return $this->triggerException(__FUNCTION__, $args, $e);
     }
 }
Ejemplo n.º 15
0
 /**
  * Internal method to replace an existing item.
  *
  * Options:
  *  - ttl <float>
  *    - The time-to-life
  *  - namespace <string>
  *    - The namespace to use
  *
  * @param  string $normalizedKey
  * @param  mixed  $value
  * @param  array  $normalizedOptions
  * @return boolean
  * @throws Exception\ExceptionInterface
  */
 protected function internalReplaceItem(&$normalizedKey, &$value, array &$normalizedOptions)
 {
     $this->memcached->setOption(MemcachedResource::OPT_PREFIX_KEY, $normalizedOptions['namespace']);
     $expiration = $this->expirationTime($normalizedOptions['ttl']);
     if (!$this->memcached->replace($normalizedKey, $value, $expiration)) {
         throw $this->getExceptionByResultCode($this->memcached->getResultCode());
     }
     return true;
 }
Ejemplo n.º 16
0
 /**
  * var olan bir cache'i değiştirir
  *
  * @param string $cache_id
  * @param object $result
  * @param integer $timeout
  * @return boolean
  */
 public function replace($cache_id, $result, $timeout = null)
 {
     if ($this->getCache($cache_id)) {
         if (is_null($timeout)) {
             return false;
         }
         return $this->memcache->replace($cache_id, $result, $timeout);
     } else {
         $this->setCache($cache_id, $result, $timeout);
     }
 }
Ejemplo n.º 17
0
 /**
  * Give (if possible) an extra lifetime to the given cache id
  *
  * @param string $id cache id
  * @param int $extraLifetime
  * @return boolean true if ok
  */
 public function touch($id, $extraLifetime)
 {
     $tmp = $this->_memcached->get($id);
     $tmp = $this->_unserialize($tmp);
     if (isset($tmp[0])) {
         $now = time();
         $expiration = $now + $extraLifetime;
         $data = $this->_serialize(array($tmp[0], $now, $ttl));
         return $this->_memcached->replace($id, $data, $extraLifetime);
     }
 }
Ejemplo n.º 18
0
 /**
  * Internal method to replace an existing item.
  *
  * @param  string $normalizedKey
  * @param  mixed  $value
  * @return boolean
  * @throws Exception\ExceptionInterface
  */
 protected function internalReplaceItem(&$normalizedKey, &$value)
 {
     $expiration = $this->expirationTime();
     if (!$this->memcached->replace($normalizedKey, $value, $expiration)) {
         if ($this->memcached->getResultCode() == MemcachedResource::RES_NOTSTORED) {
             return false;
         }
         throw $this->getExceptionByResultCode($this->memcached->getResultCode());
     }
     return true;
 }
Ejemplo n.º 19
0
 /**
  * Write to the cache
  *
  * @param $str_id
  * @param $str_session_data
  */
 private function cache($str_id, $str_session_data)
 {
     // syslog(LOG_WARNING, __METHOD__ . "() Writing to Memcache");
     try {
         $str_memcache_key = $this->getMemcacheKey($str_id);
         $bol_replaced = $this->obj_mc->replace($str_memcache_key, $str_session_data, $this->getTimeout());
         if (false === $bol_replaced) {
             $this->obj_mc->set($str_memcache_key, $str_session_data, $this->getTimeout());
         }
     } catch (\Exception $obj_ex) {
         syslog(LOG_WARNING, __METHOD__ . "() Unable to write to Memcache: " . $obj_ex->getMessage());
     }
 }
 /**
  * Read from cache.
  * @param  string key
  * @return mixed|NULL
  */
 public function read($key)
 {
     $key = urlencode($this->prefix . $key);
     $meta = $this->memcached->get($key);
     if (!$meta) {
         return NULL;
     }
     // meta structure:
     // array(
     //     data => stored data
     //     delta => relative (sliding) expiration
     //     callbacks => array of callbacks (function, args)
     // )
     // verify dependencies
     if (!empty($meta[self::META_CALLBACKS]) && !Cache::checkCallbacks($meta[self::META_CALLBACKS])) {
         $this->memcached->delete($key, 0);
         return NULL;
     }
     if (!empty($meta[self::META_DELTA])) {
         $this->memcached->replace($key, $meta, $meta[self::META_DELTA] + time());
     }
     return $meta[self::META_DATA];
 }
Ejemplo n.º 21
0
 /**
  * Save XML to cache
  *
  * @param int $userid
  * @param string $apikey
  * @param string $scope
  * @param string $name
  * @param array $args
  * @param string $xml
  * @return bool|void
  */
 public function save($userid, $apikey, $scope, $name, $args, $xml)
 {
     $key = $this->getKey($userid, $apikey, $scope, $name, $args);
     $ttl = $this->getTimeout($xml);
     $time = time();
     $timeout = $time + $ttl;
     $replace = $this->memcached->replace($key, $xml, $timeout);
     $set = $set_age = false;
     if (!$replace) {
         $set = $this->memcached->set($key, $xml, $timeout);
     }
     $replace_age = $this->memcached->replace($key . '_age', array('age' => $time, 'ttl' => $ttl), $timeout);
     if (!$replace_age) {
         $set_age = $this->memcached->set($key . '_age', array('age' => $time, 'ttl' => $ttl), $timeout);
     }
     return ($replace || $set) && ($replace_age || $set_age);
 }
Ejemplo n.º 22
0
 /**
  * Alter the TTL for a given key. Essentially, renewing it in
  * the cache.
  *
  * @param string $key
  * @param integer $ttl
  * @return boolean
  */
 public function renew($key, $ttl = self::DEFAULT_TTL)
 {
     if (!$this->hasConnection()) {
         // @codeCoverageIgnoreStart
         return false;
         // @codeCoverageIgnoreEnd
     }
     $value = $this->get($key);
     if ($value !== false) {
         try {
             return $this->memcached->replace($this->getKeyString($key), $value, $ttl);
             // @codeCoverageIgnoreStart
         } catch (\Exception $e) {
         }
     }
     // @codeCoverageIgnoreEnd
     return false;
 }
Ejemplo n.º 23
0
 /**
  * Reads from cache in bulk.
  * @param  string key
  * @return array key => value pairs, missing items are omitted
  */
 public function bulkRead(array $keys)
 {
     $prefixedKeys = array_map(function ($key) {
         return urlencode($this->prefix . $key);
     }, $keys);
     $keys = array_combine($prefixedKeys, $keys);
     $metas = $this->memcached->getMulti($prefixedKeys);
     $result = [];
     $deleteKeys = [];
     foreach ($metas as $prefixedKey => $meta) {
         if (!empty($meta[self::META_CALLBACKS]) && !Cache::checkCallbacks($meta[self::META_CALLBACKS])) {
             $deleteKeys[] = $prefixedKey;
         } else {
             $result[$keys[$prefixedKey]] = $meta[self::META_DATA];
         }
         if (!empty($meta[self::META_DELTA])) {
             $this->memcached->replace($prefixedKey, $meta, $meta[self::META_DELTA] + time());
         }
     }
     if (!empty($deleteKeys)) {
         $this->memcached->deleteMulti($deleteKeys, 0);
     }
     return $result;
 }
 /**
  * Get lock
  *
  * Acquires an (emulated) lock.
  *
  * @param	string	$session_id	Session ID
  * @return	bool
  */
 protected function _get_lock($session_id)
 {
     if (isset($this->_lock_key)) {
         return $this->_memcached->replace($this->_lock_key, time(), MEMCACHE_COMPRESSED, 5);
     }
     $lock_key = $this->_key_prefix . $session_id . ':lock';
     if (!($ts = $this->_memcached->get($lock_key))) {
         if (!$this->_memcached->set($lock_key, TRUE, MEMCACHE_COMPRESSED, 5)) {
             log_message('error', 'Session: Error while trying to obtain lock for ' . $this->_key_prefix . $session_id);
             return FALSE;
         }
         $this->_lock_key = $lock_key;
         $this->_lock = TRUE;
         return TRUE;
     }
     // Another process has the lock, we'll try to wait for it to free itself ...
     $attempt = 0;
     while ($attempt++ < 5) {
         usleep((time() - $ts) * 1000000 - 20000);
         if (($ts = $this->_memcached->get($lock_key)) < time()) {
             continue;
         }
         if (!$this->_memcached->set($lock_key, time(), MEMCACHE_COMPRESSED, 5)) {
             log_message('error', 'Session: Error while trying to obtain lock for ' . $this->_key_prefix . $session_id);
             return FALSE;
         }
         $this->_lock_key = $lock_key;
         break;
     }
     if ($attempt === 5) {
         log_message('error', 'Session: Unable to obtain lock for ' . $this->_key_prefix . $session_id . ' after 5 attempts, aborting.');
         return FALSE;
     }
     $this->_lock = TRUE;
     return TRUE;
 }
Ejemplo n.º 25
0
 public function testPassingNullKey()
 {
     $memcached = new Memcached();
     $this->assertFalse($memcached->add(null, 1));
     $this->assertFalse($memcached->replace(null, 1));
     $this->assertFalse($memcached->set(null, 1));
     $this->assertFalse($memcached->increment(null));
     $this->assertFalse($memcached->decrement(null));
 }
Ejemplo n.º 26
0
 /**
  * 替换指定键名的数据(如不存在则失败)
  *
  * @param string $key
  * @param mixed $value
  * @param int $expiration
  * @return bool
  */
 public function replace($key, $value, $expiration = 0)
 {
     return $this->memcached ? $this->memcached->replace($key, $value, $expiration) : false;
 }
Ejemplo n.º 27
0
    echo 'PHP Memcached extension was not installed';
    exit;
}
echo "Use PHP Memcached extension.<br />";
//连接
$mem = new Memcached();
$mem->addServer("127.0.0.1", 11211) or die("Could not connect");
//显示版本
$version = current($mem->getVersion());
echo "Memcached Server version:  " . $version . "<br />";
//保存数据
$mem->set('key1', 'This is first value', 60);
$val = $mem->get('key1');
echo "Get key1 value: " . $val . "<br />";
//替换数据
$mem->replace('key1', 'This is replace value', 60);
$val = $mem->get('key1');
echo "Get key1 value: " . $val . "<br />";
//保存数组
$arr = array('aaa', 'bbb', 'ccc', 'ddd');
$mem->set('key2', $arr, 60);
$val2 = $mem->get('key2');
echo "Get key2 value: ";
print_r($val2);
echo "<br />";
//删除数据
$mem->delete('key1');
$val = $mem->get('key1');
echo "Get key1 value: " . $val . "<br />";
//清除所有数据
$mem->flush();
Ejemplo n.º 28
0
 /**
  * {@inheritdoc}
  */
 public function replace($key, $value, $expire = 0)
 {
     $key = $this->encodeKey($key);
     return $this->client->replace($key, $value, $expire);
 }
Ejemplo n.º 29
0
 /**
  * Updates data in cache.
  *
  * @param string $key       The dataset Id
  * @param string $value     The data to write to cache
  * @param string $namespace The dataset namespace
  * @param int    $lifetime  Date/Time on which the cache-entry expires
  * @param string $userdata  The custom userdata to add
  *
  * @return bool TRUE on success, otherwise FALSE
  * @author Benjamin Carl <*****@*****.**>
  * @access public
  * @throws Doozr_Cache_Service_Exception
  */
 public function update($key, $value, $namespace, $lifetime = null, $userdata = null)
 {
     // Get internal used key
     $key = $this->calculateUuid($key . $namespace);
     // Build dataset from input
     $dataset = array($this->getExpiresAbsolute($lifetime), $userdata, $this->encode($value), $namespace);
     if (true !== ($result = $this->connection->replace($key, $dataset, $this->getCompress() === true ? MEMCACHE_COMPRESSED : 0, $this->getExpiresAbsolute($lifetime)))) {
         throw new Doozr_Cache_Service_Exception('Error while updating dataset!');
     }
     if ($result === true) {
         // On create we need to purge the old entry from runtime cache ...
         $this->addToRuntimeCache($key, $dataset, $namespace);
     }
     return true;
 }
Ejemplo n.º 30
0
<?php

$cache = new Memcached();
$cache->setOption(Memcached::OPT_BINARY_PROTOCOL, true);
$cache->setOption(Memcached::OPT_COMPRESSION, false);
$cache->addServer('localhost', 3434);
$cache->add("add_key", "hello", 500);
$cache->append("append_key", "world");
$cache->prepend("prepend_key", "world");
$cache->increment("incr", 2, 1, 500);
$cache->decrement("decr", 2, 1, 500);
$cache->delete("delete_k");
$cache->flush(1);
var_dump($cache->get('get_this'));
$cache->set('set_key', 'value 1', 100);
$cache->replace('replace_key', 'value 2', 200);
$cache->getStats();
$cache->quit();
sleep(1);