Recently in the project because to prevent concurrency, need to use PHP memcached extension, memcached Extension support CAS protocol, but memcache extension is not supported. When installing memcached, there is no such extension in Windows, and in order to keep the code consistent, a class that supports both Memcached and Memcache is written, so there is no need to worry about inconsistencies between production and native development code. (Note: The author usually works under Windows development, the production environment is Linux.) If you have a common development and production environment that is Linux or Mac, you will not have this problem)
The following code is directly posted:
<?php
Class zmemcached
{
static private $mem;
Simple singleton mode to reduce resource consumption
static public Function getinstance ()
{
if (self:: $mem ==null)
{
Determine if PHP has memcached extensions installed
if (class_exists (' Memcached '))
{
Self:: $mem = new Memcached ();
}
Else
{
Self:: $mem = new Memcache ();
}
}
Return self:: $mem;
}
static public function get ($key)
{
Global $INI;
if (class_exists (' Memcached '))
{
$m 1 = self::getinstance ();
Here you can add multiple Memecache servers
$m 1->addserver ($INI [' Memcachehost '], $INI [' Memcacheport ']);
$res [' value '] = $m 1->get ($key, NULL, $CAS);
$res [' cas '] = $cas;
}
Else
{
$m 1 = self::getinstance ();
$m 1->addserver ($INI [' Memcachehost '], $INI [' Memcacheport ']);
$res [' value '] = $m 1->get ($key);
}
return $res;
}
static public function set ($key, $value, $cas)
{
$value = (string) $value;
Global $INI;
if (class_exists (' Memcached '))
{
$m 1 = self::getinstance ();
$m 1->addserver ($INI [' Memcachehost '], $INI [' Memcacheport ']);
$res = $m 1->cas ($cas, $key, $value);
}
Else
{
$m 1 = self::getinstance ();
$m 1->addserver ($INI [' Memcachehost '], $INI [' Memcacheport ']);
$res = $m 1->set ($key, $value);
}
return $res;
}
}
Original link: http://back.zhizhi123.com/?p=143
Read setting Memcache value (priority support for memcached extension and CAS protocol)