This example describes the PHP memory cache memcached class. Share to everyone for your reference.
The implementation methods are as follows:
Copy Code code as follows:
? Php
Class Memcachemodel {
Private $MC = null;
/**
* Constructs a method for adding servers and creating memcahced objects
*/
function __construct () {
$params = Func_get_args ();
$MC = new Memcache;
If you have multiple memcache servers
if (count ($params) > 1) {
foreach ($params as $v) {
Call_user_func_array (Array ($MC, ' addserver '), $v);
}
If there is only one memcache server
} else {
Call_user_func_array (Array ($MC, ' addserver '), $params [0]);
}
$this->mc= $MC;
}
/**
* Get Memcached Object
* @return Object Memcached objects
*/
function Getmem () {
return $this->mc;
}
/**
* Check if MEM is connected successfully
* @return BOOL Connection successfully returns TRUE, otherwise returns false
*/
function Mem_connect_error () {
$stats = $this->mc->getstats ();
if (Emptyempty ($stats)) {
return false;
}else{
return true;
}
}
Private Function Addkey ($tabName, $key) {
$keys = $this->mc->get ($tabName);
if (Emptyempty ($keys)) {
$keys =array ();
}
If key does not exist, add a
if (!in_array ($key, $keys)) {
$keys []= $key; Add a new key to the keys in this table
$this->mc->set ($tabName, $keys, memcache_compressed, 0);
return true; Does not exist returns true
}else{
return false; Existence returns false
}
}
/**
* Add data to the Memcache
* @param string $tabName table name to cache the datasheet
* @param string $sql Use SQL as key for Memcache
* @param mixed $data data that needs to be cached
*/
function Addcache ($tabName, $sql, $data) {
$key =md5 ($sql);
If there is no
if ($this->addkey ($tabName, $key)) {
$this->mc->set ($key, $data, memcache_compressed, 0);
}
}
/**
* Get the data saved in the MEMCAHCE
* @param string $sql key with SQL
* @return Mixed returns the data in the cache
*/
function GetCache ($sql) {
$key =md5 ($sql);
return $this->mc->get ($key);
}
/**
* Delete all caches related to the same table
* @param string $tabName table name for data table
*/
function Delcache ($tabName) {
$keys = $this->mc->get ($tabName);
Delete all caches of the same table
if (!emptyempty ($keys)) {
foreach ($keys as $key) {
$this->mc->delete ($key, 0); 0 means delete immediately
}
}
Delete all SQL key for a table
$this->mc->delete ($tabName, 0);
}
/**
* Delete the cache of a single statement
* @param the SQL statement executed by string $sql
*/
function DeLone ($sql) {
$key =md5 ($sql);
$this->mc->delete ($key, 0); 0 means delete immediately
}
}
?>
I hope this article will help you with your PHP program design.