class BiMemcached{
private $id;
private $obj;
private $expiration = 0;
//new中带上唯一标示,能够创建memcached的持久化对象,所有通过相同的唯一标识值创建的实例共享同一个连接
public function __construct( $id ){
$this->obj = new Memcached( $id );
}
public function connect( $host, $port ){
$servers = $this->obj->getServerList();
if( !empty($servers) ){
foreach( $servers as $row ){
if( $row['host'] == $host && $row['port'] == $port ){
return true;
}
}
}
return $this->obj->addServer( $host, $port );
}
public function set( $key, $value, $expiration = 0 ){
if( !empty($key) ){
$this->setExpiration( $expiration );
return $this->obj->set( $key, $value, $this->expiration );
}
return false;
}
public function get( $key ){
return $this->obj->get($key);
}
//设置多个值,可以通过getMulti或get来获取值
public function setMulti( array $arr, $expiration = 0 ){
$this->setExpiration( $expiration );
if( !empty($arr) ){
return $this->obj->setMulti( $arr, $this->expiration );
}
return true;
}
public function getMulti( array $arr ){
return $this->obj->getMulti( $arr );
}
//向服务端发出一个检索keys指定的多个 key对应元素的请求。这个方法不会等待响应而是立即返回。当你需要收集元素值时, 调用Memcached::fetch()或 Memcached::fetchAll()
public function getDelayed( array $arr, $cas = false, $callBack = null ){
return $this->obj->getDelayed( $arr, $cas, $callBack );
}
public function fetch(){
return $this->obj->fetch();
}
public function fetchAll(){
return $this->obj->fetchAll();
}
//如果Memcached::OPT_COMPRESSION常量开启,这个操作会失败,并引发一个警告,因为向压缩数据 后追加数据可能会导致解压不了
public function append( $key, $value ){
$this->obj->append( $key, $value );
}
public function getOption( $option ){
return $this->obj->getOption( $option );
}
public function setOption( $option, $value ){
return $this->obj->setOption( $option, $value );
}
public function getServerList(){
return $this->obj->getServerList();
}
public function quit(){
$this->obj->quit();
}
public function setExpiration( $expiration ){
$this->expiration = !empty($expiration) && is_numeric($expiration) ? time()+ $expiration : 0;
}
public function getOption( $option ){
return $this->obj->getOption( $option );
}
public function setOption( $option, $value ){
return $this->obj->setOption( $option, $value );
}
public function getServerList(){
return $this->obj->getServerList();
}
public function quit(){
$this->obj->quit();
}
public function setExpiration( $expiration ){
$this->expiration = !empty($expiration) && is_numeric($expiration) ? time()+ $expiration : 0;
}
}
//结果回调:通过Memcached::getDelayed()或 Memcached::getDelayedBykey()方法获取元素后,为结果集中每个元素调用一次
function callBackFun( $memc, $item ){
foreach( $item as $key =>$row ){
echo "the key is".$key.", the value is ".$row."<br>";
}
}
$m = new BiMemcached('');
$m->connect('localhost', 11211);