场景*memcache操作类
memcache操作类
在实际的PHP项目中,应用单例模式可以应用到网络连接的。比如Mysql、Memcache、Redis连接等等,一般的需求通常Redis,Memcache都只有一台服务器,所以用单例模式将连接封装到getInstance(),这样做的好处是不用每次都去调用connect()方法,减少网络连接开销。PHP大部分情况是单线程同步执行的,所以整个程序只用实例化一个Redis对象即可。
Memcache.php
<?php
class MemcacheClass
{
private static $instance = null;
private $handler;
private function __construct($config)
{
if(!isset($config['host']))
{
$config['host'] = '127.0.0.1';
}
if(!isset($config['port']))
{
$config['port'] = 11211;
}
if(!isset($config['timeout']))
{
$config['timeout'] = 1;
}
$this->handler = new Memcache();
$this->handler->connect($config['host'], $config['port'], $config['timeout']);
}
public static function init($config = array())
{
if (!self::$instance) {
self::$instance = new self($config);
}
return self::$instance;
}
/**
* get cache
* @access public
* @param string $name
* @return mixed
*/
public function get($name)
{
return $this->handler->get($name);
}
/**
* set cache
* @access public
* @param string $name
* @param mixed $value
* @param integer $expire
* @return boolean
*/
public function set($name, $value, $expire = 0)
{
$this->handler->set($name, $value, MEMCACHE_COMPRESSED, $expire);
}
/**
* delete cache
* @access public
* @param string $name
* @return boolean
*/
public function rm($name, $ttl = false)
{
return $ttl === false ?
$this->handler->delete($name) :
$this->handler->delete($name, $ttl);
}
/**
* flush cache
* @access public
* @return boolean
*/
public function clear()
{
return $this->handler->flush();
}
function __destruct()
{
$this->handler->close();
}
}
test.php
include 'Memcache.class.php';
$cache = MemcacheClass::init();
Last updated
Was this helpful?