Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@deniapps
Last active September 21, 2022 20:56
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save deniapps/bb1df00975b52def248887860bb09057 to your computer and use it in GitHub Desktop.
Save deniapps/bb1df00975b52def248887860bb09057 to your computer and use it in GitHub Desktop.
The wrapper of PHP-Memcached
/**
* There are two PHP Memcache extensions available from the PHP Extension Community Library: PHP Memcached and PHP Memcache.
* This wrapper is for "PHP Memcached"
*
* Usuage: see in the comment
*
*
*/
class CacheMemcached
{
public $iTtl = 600; // Time To Live (number of second)
public $bEnabled = true; // Memcached enabled?
public $oCache = null;
// constructor
public function __construct()
{
if (class_exists('Memcached')) {
$this->oCache = new Memcached();
if (!$this->oCache->addServer('localhost', 11211)) {
$this->oCache = null;
$this->bEnabled = false;
}
} else {
$this->bEnabled = false;
}
}
// get data from cache server
public function getData($sKey)
{
$vData = $this->oCache->get($sKey);
return false === $vData ? null : $vData;
}
// save data to cache server
public function setData($sKey, $vData)
{
return $this->oCache->set($sKey, $vData, $this->iTtl);
}
// delete data from cache server
public function delData($sKey)
{
return $this->oCache->delete($sKey);
}
// flush data from cache server
public function flushData()
{
return $this->oCache->flush();
}
}
@deniapps
Copy link
Author

An example to use this Wrapper:

$key = 'MYDATA';

$mData = '';

$oCache = new CacheMemcached();
if ($oCache->bEnabled) {
    $mData = $oCache->getData($key);
}
else {
    // your code to fetch data ...
    $mData = fetchMyData();
    if ($oCache->bEnabled) { // if Memcache enabled
        $oCache->setData($key, $mData);
    }
}
echo $mData;

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment