>PHP: Memcache Functions - Manual

MANUAL DE PHP

(y algo mas)windsurf pozo izquierdo
Google
search for in the  
ELMARRAJO.COM mysql bulma desarrollo web linux fedora html ayuda

windsurf mercedes camper

LXXVII. Memcache Functions

Introducción

Memcache module provides handy procedural and object oriented interface to memcached, highly effective caching daemon, which was especially designed to decrease database load in dynamic web applications.

More information about memcached can be found at http://www.danga.com/memcached/.

Requisitos

This module uses functions of zlib to support on-the-fly data compression. Zlib is required to install this module.

PHP 4.3.3 or newer is required to use the memcache extension.

Instalación

Esta extension PECL no esta ligada a PHP. Mas informacion sobre nuevos lanzamientos, descargas ficheros de fuentes, informacion sobre los responsables asi como un 'CHANGELOG', se puede encontrar aqui: http://pecl.php.net/package/memcache.

In order to use these functions you must compile PHP with Memcache support by using the --enable-memcache[=DIR] option.

Windows users will enable php_memcache.dll inside of php.ini in order to use these functions. Podeis descargar esta DLL de las extensiones PECL desde la pagina PHP Downloads o desde http://snaps.php.net/.

Constantes predefinidas

Tabla 1. MemCache Constants

NameDescription
MEMCACHE_COMPRESSED (integer) Used to turn on-the-fly data compression on with Memcache::set(), Memcache::add(), y Memcache::replace().

Configuración en tiempo de ejecución

Esta extensión no tiene directivas de configuración en php.ini.

Tipos de recursos

There is only one resource type used in memcache module - it's the link identifier for a cache server connection.

Ejemplos

Ejemplo 1. memcache extension overview example

<?php

$memcache
= new Memcache;
$memcache->connect('localhost', 11211) or die ("Could not connect");

$version = $memcache->getVersion();
echo
"Server's version: ".$version."<br/>\n";

$tmp_object = new stdClass;
$tmp_object->str_attr = 'test';
$tmp_object->int_attr = 123;

$memcache->set('key', $tmp_object, false, 10) or die ("Failed to save data at the server");
echo
"Store data in the cache (data will expire in 10 seconds)<br/>\n";

$get_result = $memcache->get('key');
echo
"Data from the cache:<br/>\n";

var_dump($get_result);

?>

In the above example, an object is being saved in the cache and then retrieved back. Object and other non-scalar types are serialized before saving, so it's impossible to store resources (i.e. connection identifiers and others) in the cache.

Tabla de contenidos
Memcache::add -- Add an item to the server
Memcache::addServer -- Add a memcached server to connection pool
Memcache::close -- Close memcached server connection
Memcache::connect -- Open memcached server connection
memcache_debug -- Turn debug output on/off
Memcache::decrement -- Decrement item's value
Memcache::delete -- Delete item from the server
Memcache::flush -- Flush all existing items at the server
Memcache::get -- Retrieve item from the server
Memcache::getExtendedStats -- Get statistics from all servers in pool
Memcache::getStats -- Get statistics of the server
Memcache::getVersion -- Return version of the server
Memcache::increment -- Increment item's value
Memcache::pconnect -- Open memcached server persistent connection
Memcache::replace -- Replace value of the existing item
Memcache::set -- Store data at the server
Memcache::setCompressThreshold -- Enable automatic compression of large values


add a note add a note User Contributed Notes
Memcache Functions
iliya at pisem dot net
19-Jan-2006 12:35
one more "intelligent" cache aggregator:
https://svn.shadanakar.org/onPHP/ trunk/core/Cache/AggregateCache.class.php
can be used with several cache connectors - memcached, filesystem, etc.
(remove whitespace manually)
Gregor J. Rothfuss
21-Nov-2005 09:18
The next version will have failover. It's been committed three weeks ago. Usage notes here: http://www.codecomments.com/archive367-2005-10-659421.html
Ron
14-Sep-2005 01:19
An improvement to the above:

The above class will cause an error if all cache servers are down.  The preferred behavior is to just have a cache miss (or take no action in the case of write operations) and return false, so the app can run in non-cached mode if all cache servers are down.

To make this happen, simply change the connection usage to look something like this in each affected function.  This code is for the get() function:

       $con = $this->_getConForKey($key);
       if ($con === false) return false;
       return $con->get($key);

Similarly, the affected code in the set() function would look like this:
   $con = $this->_getConForKey($key);
   if ($con === false) return false;
   return $con->set($key, $var, $compress, $expire);

Modify each function accordingly, and if all of your cache servers are down, you can still function (although more slowly due to the 100% cache miss rate).
Ron
14-Sep-2005 10:20
Here is a simple memcached aggregator class which distributes the cache among multiple cache servers.  If a server fails, the load is redistributed automatically.  It uses persistent connections.

The constructor takes an array of arrays, with each inner array representing a server, with a 'server' (string) attribute that is the IP addres or host name of the memcached server, and a 'port' (int) attribute that is the port number on which memcached is running on the server.

All of the existing memcached API functions are implemented except getStats() and getVersion(), which are server-specific.

<?php
class MemcachedAggregator {
   var
$connections;

   public function
__construct($servers) {
  
// Attempt to establish/retrieve persistent connections to all servers.
   // If any of them fail, they just don't get put into our list of active
   // connections.
  
$this->connections = array();
   for (
$i = 0, $n = count($servers); $i < $n; $i++) {
      
$server = $servers[$i];
      
$con = memcache_pconnect($server['host'], $server['port']);
       if (!(
$con == false)) {
      
$this->connections[] = $con;
       }
   }
   }

   private function
_getConForKey($key) {
  
$hashCode = 0;
   for (
$i = 0, $len = strlen($key); $i < $len; $i++) {
      
$hashCode = (int)(($hashCode*33)+ord($key[$i])) & 0x7fffffff;
   }
   if ((
$ns = count($this->connections)) > 0) {
       return
$this->connections[$hashCode%$ns];
   }
   return
false;
   }

   public function
debug($on_off) {
  
$result = false;
   for (
$i = 0; $i < count($connections); $i++) {
       if (
$this->connections[$i]->debug($on_off)) $result = true;
   }
   return
$result;
   }

   public function
flush() {
  
$result = false;
   for (
$i = 0; $i < count($connections); $i++) {
       if (
$this->connections[$i]->flush()) $result = true;
   }
   return
$result;
   }

/// The following are not implemented:
///getStats()
///getVersion()

  
public function get($key) {
   if (
is_array($key)) {
      
$dest = array();
       foreach (
$key as $subkey) {
      
$val = get($subkey);
       if (!(
$val === false)) $dest[$subkey] = $val;
       }
       return
$dest;
   } else {
       return
$this->_getConForKey($key)->get($key);
   }
   }

   public function
set($key, $var, $compress=0, $expire=0) {
   return
$this->_getConForKey($key)->set($key, $var, $compress, $expire);
   }

   public function
add($key, $var, $compress=0, $expire=0) {
   return
$this->_getConForKey($key)->add($key, $var, $compress, $expire);
   }

   public function
replace($key, $var, $compress=0, $expire=0) {
   return
$this->_getConForKey($key)->replace
      
($key, $var, $compress, $expire);
   }

   public function
delete($key, $timeout=0) {
   return
$this->_getConForKey($key)->delete($key, $timeout);
   }

   public function
increment($key, $value=1) {
   return
$this->_getConForKey($key)->increment($key, $value);
   }

   public function
decrement($key, $value=1) {
   return
$this->_getConForKey($key)->decrement($key, $value);
   }

}
?>

Citas célebres

La fuente de toda poesía es el sentimiento profundo de lo inexpresable.

Lucien Arréat
Filósofo francés
(1841-1922)
Citas en tu mail
©Contenidos Gratis

Ilusiones Opticas
ilusion_optica_069.jpg
Contenidos Web

Chiste de... Camareros
Watson y Holmes

- ¿Qué tipo de queso quiere, ¿señor Holmes?

- El-emental, querido Watson.
Chistes en tu mail
©ContenidosGratis

Humor Gráfico
humor_grafico_062.jpg
Contenidos Web

Inicio | Acción | Estrategia | Palabras | Puzzles | Solitarios | Foro Trucos
Cake ManiaCake Mania
Jugadores: 6835
Categoría del juego: Acción
Objetivo del juego: Ayuda a Jill a recuperar la pastelería de su abuela llevando su propia pastelería; consigue clientes y gana dinero.
Rainbow WebRainbow Web
Jugadores: 2199
Categoría del juego: Puzzles
Objetivo del juego: Rompe un pegajoso hechizo y salva un reino de fantasía en Rainbow Web. Tendrás toneladas de diversión mientras juegas a este mágico desafío para la mente.
Mahjongg FortunaMahjongg Fortuna
Jugadores: 12462
Categoría del juego: Solitarios
Objetivo del juego: Velocidad y habilidad mental son las armas más importantes en esta versión de un antiguo juego asiático. Despeja el tablero lo antes posible haciendo clic en las fichas iguales y gánate la fama eterna de la puntuación más alta.
Chainz 2Chainz 2
Jugadores: 6955
Categoría del juego: Puzzles
Objetivo del juego: Entra en el mundo de las combinaciones con Chainz 2: Relinked, emocionante secuela del exitazo del año pasado, Chainz. Gira eslabones y crea combinaciones de 3 ó más.
DeliciousDelicious
Jugadores: 4405
Categoría del juego: Acción
Objetivo del juego: ¿Eres un as de la multitarea? ¿Quieres que tus clientes estén contentos? ¡Pues Delicious es tu juego! Sacia el apetito de los clientes y tenlos contentos; ¡no te arriesgues!
BookwormBookworm
Jugadores: 4568
Categoría del juego: Palabras
Objetivo del juego: Junta las letras para formar palabras. ¡Las palabras más largas valen más puntos!
ZumaZuma
Jugadores: 4976
Categoría del juego: Acción
Objetivo del juego: Controla el ídolo de la rana de piedra de los antiguos Zuma en este intrigante enigma de acción. ¡Dispara bolas para formar conjuntos de tres, pero si dejas que lleguen a la calavera dorada morirás!
Jewel of AtlantisJewel of Atlantis
Jugadores: 3798
Categoría del juego: Puzzles
Objetivo del juego: Descubre la ciudad hundida de la Atlántida y busca valiosos tesoros. Viaja más allá de las profundidades del mar y vive trepidantes aventuras en Jewel of Atlantis.
Jewel QuestJewel Quest
Jugadores: 3727
Categoría del juego: Puzzles
Objetivo del juego: Convierte la arena de la antigua selva en oro tan rápido como puedas juntando grupos de 3 elementos. ¡Los grupos más grandes valen más puntos!
Bejeweled 2Bejeweled 2
Jugadores: 3659
Categoría del juego: Puzzles
Objetivo del juego: Con cuatro modos de juego únicos y fascinantes, nuevas piezas de juego explosivas e imponentes fondos planetarios, Bejeweled 2 es mucho más adictivo que nunca.
Contenidos gratis en tu webSiguiente >>

Fotos divertidas
fotos_increibles_0390.jpg
Contenidos Web
microrobots avion deportes riesgo recetas cocina canaria juegos online gratis moto motociclismo horoscopos naranjas valencianas surf canarias montañismo ciudades turismo postales gratis library Horoscopos Diarios Windsurf Canarias
fregadero microondas placa electrica bañopreparar camper pantalla plananevera compresor electricacamper fiat ducato camper baño quimicomampara enrollable bañocamper aire climatizadofurgoneta surf windsurffurgoneta surf windsurftelevisor furgonetas camperfurgonetas camper cama

Sudoku del día
Nivel de dificultad: Fácil



Cómo jugar:
El juego consiste en colocar los números del 1 al nueve de tal forma que no se repita el mismo número en la columna, fila y caja (bloques 3x3 enmarcados).

©Contenidos Gratis | Sudoku en tu mail
Sucedió el...

30 de agosto de 1617

Fallece Santa Rosa de Lima, por la que se celebra el "Día de la Patrona de América".
Efemérides en tu mail
©Contenidos Gratis
windsurf canarias youtube porno canarias baleares valencia madrid