In addition to memcache this more commonly used PHP Operation class Library, we may also be very familiar with a memory cache of things, that is redis, we share this PHP technical article, is about how to use PHP to operate Redis this memory Cache tool class Library OH.
PHP Redis Cache operation
<? php
/ **
* Redis cache operation
* @author hxm
* @version 1.0
* @since 2015.05.04
* /
class RCache extends Object implements CacheFace
{
private $ redis = null; // redis object
private $ sId = 1; // servier service ID
private $ con = null; // link resource
/ **
* Initialize Redis
*
* @return Object
* /
public function __construct ()
{
if (! class_exists ('Redis'))
{
throw new QException ('PHP extension does not exist: Redis');
}
$ this-> redis = new Redis ();
}
/ **
* Link memcahce service
*
* @access private
* @param string $ key keyword
* @param string $ value cache content
* @return array
* /
private function connect ($ sid)
{
$ file = $ this-> CacheFile ();
require $ file;
if (! isset ($ cache))
{
throw new QException ('Cache configuration file does not exist'. $ file);
}
$ server = $ cache [$ this-> cacheId];
$ sid = isset ($ sid) == 0? $ this-> sId: $ sid; // memcache service selection
if (! $ server [$ sid])
{
throw new QException ('The cache server configuration file for the current operation does not exist');
}
$ host = $ server [$ sid] ['host'];
$ port = $ server [$ sid] ['port'];
try {
$ this-> redis-> connect ($ host, $ port);
} catch (Exception $ e) {
exit ('memecache connection failed, error message:'. $ e-> getMessage ());
}
}
/ **
* Write cache
*
* @access private
* @param string $ key keyword
* @param string $ value cache content
* @return array
* /
public function set ($ key, $ value, $ sid, $ expire = 0)
{
$ data = $ this-> get ($ key, $ sid); // if the key value already exists
if ($ data)
{
return $ this-> redis-> getset ($ key, $ value);
} else {
return $ this-> redis-> set ($ key, $ value);
}
}
/ **
* Read cache
*
* @access private
* @param string $ key keyword
* @param int $ sid select the memcache server
* @return array
* /
public function get ($ key, $ sid)
{
$ this-> connect ($ sid);
return $ this-> redis-> get ($ key);
}
/ **
* Clean (delete) all elements that have been stored
*
* @access private
* @return array
* /
public function flush ()
{
$ this-> connect ();
return $ this-> redis-> flushall ();
}
/ **
* Delete cache
*
* @access private
* @param string $ key keyword
* @param int $ sid select the memcache server
* @return array
* /
public function remove ($ key, $ sid)
{
$ this-> connect ();
return $ this-> redis-> del ($ key);
}
/ **
* Destructor
* Finally close memcache
* /
public function __destruct ()
{
if ($ this-> redis)
{
$ this-> redis-> close ();
}
}
}
The above is the entire contents of this article, I hope you can enjoy.