Memcached::set

(PECL memcached >= 0.1.0)

Memcached::setСохраняет запись

Описание

public Memcached::set(string $key, mixed $value, int $expiration = 0): bool

Memcached::set() сохраняет значение value на memcache сервере под указанным ключом key. Параметр expiration может быть использован для контроля, когда срок действия значения считается истёкшим.

Значение может быть любым доступным в PHP типом, кроме ресурса, потому что этот тип не может быть представлен в сериализованном виде. Если установлен параметр Memcached::OPT_COMPRESSION, то сериализованное значение будет также сжато перед сохранением.

Список параметров

key

Ключ, под которым сохраняется значение.

value

Сохраняемое значение.

expiration

Время хранения объекта, по умолчанию равно 0. Подробнее об этом рассказывает раздел «Время хранения объекта».

Возвращаемые значения

Функция возвращает true, если выполнилась успешно, или false, если возникла ошибка. Вызывайте метод Memcached::getResultCode(), если требуется.

Примеры

Пример #1 Пример использования Memcached::set()

<?php
$m
= new Memcached();
$m->addServer('localhost', 11211);

$m->set('int', 99);
$m->set('string', 'a simple string');
$m->set('array', array(11, 12));
/* время хранения записи с ключом 'object' установлено в 5 минут */
$m->set('object', new stdClass, time() + 300);


var_dump($m->get('int'));
var_dump($m->get('string'));
var_dump($m->get('array'));
var_dump($m->get('object'));
?>

Вывод приведённого примера будет похож на:

int(99)
string(15) "a simple string"
array(2) {
  [0]=>
  int(11)
  [1]=>
  int(12)
}
object(stdClass)#1 (0) {
}

Смотрите также

  • Memcached::setByKey() - Сохраняет элемент на конкретном сервере
  • Memcached::add() - Добавляет элемент с новым ключом
  • Memcached::replace() - Заменяет существующую запись с указанным ключом

Добавить

Примечания пользователей 5 notes

up
14
HaxxxxaH
9 years ago
@PeterNYou said that this was wrong:$m->set('object', new stdclass, time() + 300);And instead this is the correct way:$m->set('object', new stdclass, 300);When actually, they are both correct. Expiration looks at the time given, if the number is less than or equal to 30 days(60 * 60 * 24 * 30 = 2,592,000), then it expires in that many seconds. If the number is greater than 30 days, then it expires at that UNIX time.
up
6
Matthew Minix
11 years ago
Unlike Memcache, Memcached will not replace spaces in keys with underscores for you, and will instead send the key as provided which will cause an error that can result in keys and values being mismatched.  You can avoid this problem by removing/replacing spaces before storage or setting the option Memcached::OPT_BINARY_PROTOCOL to true.
up
9
PeterN
9 years ago
In the example it shows:/* expire 'object' key in 5 minutes */$m->set('object', new stdclass, time() + 300);But this is wrong.It will not expire, at least, not for a long long time.So instead of time() + seconds, you use:$m->set('object', new stdclass, 300);And it will correctly expire after 5 minutes.Note: Using memcached 2.1.0 stable through PECL.
up
7
Anonymous
11 years ago
00 = MEMCACHED_SUCCESS01 = MEMCACHED_FAILURE02 = MEMCACHED_HOST_LOOKUP_FAILURE // getaddrinfo() and getnameinfo() only03 = MEMCACHED_CONNECTION_FAILURE04 = MEMCACHED_CONNECTION_BIND_FAILURE // DEPRECATED see MEMCACHED_HOST_LOOKUP_FAILURE05 = MEMCACHED_WRITE_FAILURE06 = MEMCACHED_READ_FAILURE07 = MEMCACHED_UNKNOWN_READ_FAILURE08 = MEMCACHED_PROTOCOL_ERROR09 = MEMCACHED_CLIENT_ERROR10 = MEMCACHED_SERVER_ERROR // Server returns "SERVER_ERROR"11 = MEMCACHED_ERROR // Server returns "ERROR"12 = MEMCACHED_DATA_EXISTS13 = MEMCACHED_DATA_DOES_NOT_EXIST14 = MEMCACHED_NOTSTORED15 = MEMCACHED_STORED16 = MEMCACHED_NOTFOUND17 = MEMCACHED_MEMORY_ALLOCATION_FAILURE18 = MEMCACHED_PARTIAL_READ19 = MEMCACHED_SOME_ERRORS20 = MEMCACHED_NO_SERVERS21 = MEMCACHED_END22 = MEMCACHED_DELETED23 = MEMCACHED_VALUE24 = MEMCACHED_STAT25 = MEMCACHED_ITEM26 = MEMCACHED_ERRNO27 = MEMCACHED_FAIL_UNIX_SOCKET // DEPRECATED28 = MEMCACHED_NOT_SUPPORTED29 = MEMCACHED_NO_KEY_PROVIDED /* Deprecated. Use MEMCACHED_BAD_KEY_PROVIDED! */30 = MEMCACHED_FETCH_NOTFINISHED31 = MEMCACHED_TIMEOUT32 = MEMCACHED_BUFFERED33 = MEMCACHED_BAD_KEY_PROVIDED34 = MEMCACHED_INVALID_HOST_PROTOCOL35 = MEMCACHED_SERVER_MARKED_DEAD36 = MEMCACHED_UNKNOWN_STAT_KEY37 = MEMCACHED_E2BIG38 = MEMCACHED_INVALID_ARGUMENTS39 = MEMCACHED_KEY_TOO_BIG40 = MEMCACHED_AUTH_PROBLEM41 = MEMCACHED_AUTH_FAILURE42 = MEMCACHED_AUTH_CONTINUE43 = MEMCACHED_PARSE_ERROR44 = MEMCACHED_PARSE_USER_ERROR45 = MEMCACHED_DEPRECATED46 = MEMCACHED_IN_PROGRESS47 = MEMCACHED_SERVER_TEMPORARILY_DISABLED48 = MEMCACHED_SERVER_MEMORY_ALLOCATION_FAILURE49 = MEMCACHED_MAXIMUM_RETURN /* Always add new error code before */11 = MEMCACHED_CONNECTION_SOCKET_CREATE_FAILURE = MEMCACHED_ERROR
up
4
miha at hribar dot info
16 years ago
The method correctly returns false if you set the value to false. This means that in order to have proper fault checking mechanism in place you need to check the result code.<?php$Memcached = new Memcached();$Memcached->addServer('localhost', 11211);$Memcached->set('key', false);var_dump($Memcached->get('key'));      // boolean falsevar_dump($Memcached->getResultCode()); // int 0 which is  Memcached::RES_SUCCESS  ?>
To Top