缓存数据

   
安装后,就可以让 Memcache 运行了。

    Memcache
通常用于存储对象,但是它可以存储可序列化的任何 PHP 变量,例如字符串。Memcache 有一个面向过程和一个面向对象的 API。不管您使用哪一个变量,您必须提供四个实参才能把变量存储到缓存中:

惟一关键字

   
关键字用于从缓存中检索相关数据。如果每条记录都有一个惟一 ID,则可能足以作为缓存关键字,但是您可以策划其他模式来满足需求。

要缓存的变量

   
变量可以是任意类型,只要它可以被序列化为持久的变量并且可以取消序列化为检索的变量。
    
用于启用通过 zlib 进行动态压缩的布尔值。
   
压缩将节省缓存中的内存 —— 虽然处理数据时都要以保存和恢复为代价。 
   
以秒为单位指定的过期时间
   
当缓存的数据过期时,它将被自动删除。如果将此值设为 0,则该条目永远不会在缓存中过期。使用 Memcache API delete() 函数删除这样一个永久对象。
   
下面的代码将使用面向对象的 Memcache 扩展 API 来创建、存储和检索一个简单对象。

清单 6. 创建、缓存和检索 PHP 对象 <?xml:namespace prefix = o ns = "urn:schemas-microsoft-com:office:office" />

<?php

 

class myCache extends Memcache {

function getInstance() {

static $instance;

 

if ( ! isset( $instance )) {

$instance = new Memcache;

$instance->connect( '198.168.0.1' );

}

 

return $instance;

}

 

function close( ) {

if ( isset( $instance ) ) {

$instance->close();

$instance = null;

}

}

}

 

class myDatum {

var $values = array(

'description' => null,

'price' => null,

'weight' => null

);

 

function myDatum( $settings ) {

foreach ( $settings as $key => $value ) {

if ( ! array_key_exists( $key, $this->values ) ) {

die( "Unknown attribute: $key" );

}

 

$this->values{ $key } = $value;

}

}

 

function set( $key=null, $value=null ) {

if ( is_null( $key ) ) {

die( "Key cannot be null" );

}

 

if ( ! array_key_exists( $key, $this->values ) ) {

die( "Unknown attribute: $key" );

}

 

if ( ! is_null( $value ) ) {

$this->values{ $key } = $value;

}

 

return( $this->values{ $key } );

}

 

function get( $key=null ) {

return( $this->set( $key, null ) );

}

}

 

 

$datum = new myDatum(

array(

'description' => 'ball',

'price' => 1.50,

'weight' => 10

)

);

 

print $datum->get( 'description' ) . "\n";

 

$cache = myCache::getInstance( );

 

if ( $cache->set( $datum->get( 'description' ), $datum, false, 600 ) ) {

print( 'Object added to cache' . "\n");

}

 

$cache->close();

 

 

$new_cache = myCache::getInstance( );

 

$new_datum = $new_cache->get( $datum->get( 'description' ) );

 

if ( $new_datum !== false ) {

print( 'Object retrieved from cache' . "\n");

print $new_datum->get( 'description' ) . "\n";

}

 

print_r( $new_cache->getExtendedStats() );

 

$new_cache->close();

?>

    myCache 类是单件并提供指向缓存的单独的开放连接。myDatum 类代表了所有对象:它有一系列属性(实现为散列),以及一个 getter 和一个 setter 方法。要创建 myDatum 对象,请把一个值散列传递给其构造函数。要设定属性,请调用带有属性名的 set() 作为字符串和值。要获得属性,请调用带有属性名的 get()

   
以上代码中的最后几行将创建对象、把对象存储到缓存中并检索对象。Memcache API 的倒数第二行、部分将显示缓存的统计信息。如果使用新的 PHP 命令行解释程序运行清单 6,则应当会看到类似清单 7 所示的内容