downloads | documentation | faq | getting help | mailing lists | licenses | wiki | reporting bugs | php.net sites | links | conferences | my php.net

search for in the

Memcache::setCompressThreshold> <Memcache::replace
Last updated: Fri, 20 May 2011

view this page in

Memcache::set

(PECL memcache >= 0.2.0)

Memcache::setGuarda datos en el servidor

Descripción

bool Memcache::set ( string $key , mixed $var [, int $flag [, int $expire ]] )

Memcache::set() guarda un valor var con una key en el servidor memcached. El parámetro expire es el tiempo de expiración en segundos. Si es 0, el valor nunca expira (pero el servidor memcached no garantiza que este valor será guardado para siempre, puede ser eliminado de la caché para hacer espacio para otros valores). Se puede usar la constante MEMCACHE_COMPRESSED en el valor del flag si quiere utilizar compresión al momento (usando zlib).

Note:

Recuerde que variables de recursos (ej. ficheros y descriptores de conexiones) no pueden guardarse en caché, porque no pueden ser representados adecuadamente de forma serializada.

También se puede usar la función memcache_set().

Parámetros

key

La clave que quedará asociada con el valor.

var

La variable a guardar. Cadenas y enteros se guardan tal y como son, otros tipos se guardan serializados.

flag

Use MEMCACHE_COMPRESSED para guardar datos comprimidos (usa zlib).

expire

Tiempo de expiración del valor. Si es iqual a cero, el valor nunca expirará. También puedes usar Unix timestamp o el número de segundos empezando desde la fecha actual, el valor no puede exceder de 2592000 segundos (30 días).

Valores devueltos

Devuelve TRUE en caso de éxito o FALSE en caso de error.

Ejemplos

Example #1 Ejemplo de Memcache::set()

<?php
/* API por procesos */

/* Conectar al servidor memcached */
$memcache_obj memcache_connect('memcache_host'11211);

/*
Establecer el valor según la key 'var_key'
usando 0 como valor del flag, no será usada compresión
el tiempo de expiración es de 30 segundos
*/
memcache_set($memcache_obj'var_key''some variable'030);

echo 
memcache_get($memcache_obj'var_key');

?>

Example #2 Ejemplo de Memcache::set()

<?php
/* API OO */

$memcache_obj = new Memcache;

/* connect to memcached server */
$memcache_obj->connect('memcache_host'11211);

/*
Establece el valor según la llave 'var_key', usando compresión al momento
expira en 50 segundos
*/
$memcache_obj->set('var_key''some really big variable'MEMCACHE_COMPRESSED50);

echo 
$memcache_obj->get('var_key');

?>

Ver también



Memcache::setCompressThreshold> <Memcache::replace
Last updated: Fri, 20 May 2011
 
add a note add a note User Contributed Notes Memcache::set
wbonde at yakabod dot com 21-Jan-2011 08:27
The max time for expiration (without having to worry about deletions when necessary as with 0 seconds) is 2,592,000 seconds (30 days).

Specifying an expiration value above that will return false, but will NOT throw in error so it is easy to miss.
duerra at nospam dot yahoo dot com 18-Nov-2010 12:04
If you're interested in using compression, please note that, at least for PHP version 5.3.2 and Memcache version 3.0.4, when retrieving a key who's value is a numeric or boolean type, PHP throws a notice of the following:

Message: MemcachePool::get(): Failed to uncompress data

The way around this is to test your variable type before setting or adding it to Memcache, or even cast it as a string. 

<?php
$key
= 'mc_key';
$value = 12345;
$compress = is_bool($value) || is_int($value) || is_float($value) ? false : MEMCACHE_COMPRESSED;

$mc= new Memcache;
$mc->connect('localhost', 11211);
$mc->set($key, $value, $compress);

echo
$mc->get($key);

//Alternative is to cast the variable
$value = is_scalar($value) ? (string)$value : $value;
$mc->set($key, $value, MEMCACHE_COMPRESSED);
?>
effeesse gmail com 23-Apr-2010 08:06
if you want to cache an image created on-the-fly you can do:

<?php
ob_start
();
imagepng($image);
$memcache->set("my_image", ob_get_contents(), false, $cache_time);
ob_end_clean();
?>

then you could access the chached image as simple variable:
<?php $my_image = $memcache->get("my_image"); ?>

so, in short, you have to buffer the output
argyleblanket 25-Jun-2008 12:12
Using set more than once for the same key seems to have unexpected results - it does not behave as a "replace," but instead seems to "set" more than one value for the same key.  "get" may return any of the values.

This was tested on a multiple-server setup - behaviour may be different if you only have one server.

Remedy is to use a combination of replace and set:

<?php
$result
= $memcache->replace( $key, $var );
if(
$result == false )
{
   
$result = $memcache->set( $key, $var );
}
?>
jakub dot lopuszanski at nasza-klasa dot pl 14-Apr-2008 02:45
The lowest byte of the int is reserved for pecl/memcache internal usage (e.g. to indicate compression and serialization status).
Stephen from veedow.com 09-Apr-2008 02:07
I ran into problems using the MEMCACHE_COMPRESSED flag when storing small amounts of data, such as an integers.

For expample.

<?php
Memcache
::set('integer', 123456, MEMCACHE_COMPRESSED);
//would return true

Memcache::get('integer');
//would return false
?>

This problem went away when I removed the MEMCACHE_COMPRESSED flag for values that were small.
phalcos 24-Sep-2007 06:46
Here is a very visual example on how to use the memcache. It sets the key 'time' to the current time.
Put the example code in an empty page and keep reloading it.
As you can see, after 10 seconds your memcache key will be able to update with a new timestamp.

<?php

$memcache_obj
= new Memcache;
$memcache_obj->connect('127.0.0.1', 11211);

if (
$memcache_obj->get('time') == "") {
       
$date = date("H:i:s");
       
$memcache_obj->set('time', $date, MEMCACHE_COMPRESSED, 10);
}

echo
"At ".date("H:i:s").", your key is ".$memcache_obj->get('time');

?>
Sc00bz 19-Jul-2007 08:20
This is just two minor things about memcache that might not be perfectly clear, the limits on key and data sizes and what happen to flags in the memcache protocol.

* There is a max key size of 250 anything bigger gets truncated. There is also a (1MB - 42 bytes) limit on the data.

* In the memcache protocol there is a 16bit, 32bit in newer version, flag that you can set to whatever you want because memcache doesn't do anything with the flags. The php api doesn't let you get the flags because php uses the flags for php's own use such as "MEMCACHE_COMPRESSED" and I decided to test if it was doing something because it wasn't part of the memcache protocol.

<?php
$memcache
= new Memcache();
$memcache->connect("127.0.0.1", 11211);

// Since memcache truncates the keys at 250 bytes both the get "250 a's" and "251 a's" will find the key in the cache
echo "*** Truncate key test ***<br>";
echo
"set 251: " . ($memcache->set(str_repeat("a", 251), "value", 0, 1) ? "t" : "f") . "<br>";

echo
"get 249: " . (($ret = $memcache->get(str_repeat("a", 249))) !== false ? "'$ret'" : "f") . "<br>";
echo
"get 250: " . (($ret = $memcache->get(str_repeat("a", 250))) !== false ? "'$ret'" : "f") . "<br>";
echo
"get 251: " . (($ret = $memcache->get(str_repeat("a", 251))) !== false ? "'$ret'" : "f") . "<br>";
echo
"delete: " . ($memcache->delete(str_repeat("a", 250)) ? "t" : "f") . "<br><br>";

echo
"*** Compress value test ***<br>";
echo
"set 1024*1024-42: " . ($memcache->set("test", str_repeat("a", 1024*1024-42), 0, 1) ? "t" : "f") . "<br>";
echo
"set 1024*1024-41: " . ($memcache->set("test", str_repeat("a", 1024*1024-41), 0, 1) ? "t" : "f") . "<br>";
echo
"set 1024*1024 compressed: " . ($memcache->set("test", str_repeat("a", 1024*1024), MEMCACHE_COMPRESSED, 1) ? "t" : "f") . "<br>";
echo
"delete: " . ($memcache->delete("test") ? "t" : "f") . "<br>";
$memcache->close();
?>

Output:
*** Truncate key test ***
set 251: t
get 249: f
get 250: 'value'
get 251: 'value'
delete: t

*** Compress value test ***
set 1024*1024-42: t
set 1024*1024-41: f
set 1024*1024 compressed: t
delete: t

 
show source | credits | stats | sitemap | contact | advertising | mirror sites