5

我有一个与 memcache 服务器交互的类。我有不同的功能来插入、删除和检索数据。最初每个函数都会调用memcache_connect(),但是这是不必要的,例如:

mc->insert()  
mc->get()  
mc->delete() 

将建立三个 memcache 连接。我通过为该类创建一个构造来解决此问题:

function __construct() {
    $this->mem = memcache_connect( ... );
}

然后$this->mem在需要资源的地方使用,因此三个函数中的每一个都使用相同的memcache_connect资源。

没关系,但是如果我在其他类中调用该类,例如:

class abc
{
    function __construct() {
        $this->mc = new cache_class;
    }
}    
class def
{
    function __construct() {
        $this->mc = new cache_class;
    }
}

那么它仍然在打两个memcache_connect电话,而它只需要一个。

我可以用全局变量来做到这一点,但如果我不需要,我宁愿不使用它们。

全局变量实现示例:

$resource = memcache_connect( ... );

class cache_class
{
    function insert() {
        global $resource;
        memcache_set( $resource , ... );
    }
    function get() {
        global $resource;
        return memcache_get( $resource , ... );
    }

}

那么无论该类被调用多少次,都只会调用一次memcache_connect

有没有办法做到这一点,或者我应该只使用全局变量?

4

4 回答 4

9

我将使用单例模式编写另一个类来获取内存缓存的唯一实例。像这样 -

class MemCache 
{ 
  private static $instance = false;   
  private function __construct() {}

  public static function getInstance()
  { 
    if(self::$instance === false)
    { 
      self::$instance = memcache_connect(); 
    } 

    return self::$instance; 
  } 
}

和用法——

$mc = MemCache::getInstance();
memcache_get($mc, ...)
...
于 2009-02-15T11:41:56.587 回答
5

传入 MC 实例:

class abc
{
    function __construct($mc) {
        $this->mc = $mc;
    }
}    
class def
{
    function __construct($mc) {
        $this->mc = $mc;
    }
}

$mc = new cache_class;
$abc = new abc($mc);

等等

于 2009-02-15T11:36:31.670 回答
2

我想你在这里寻找静态属性。

class mc {
    private static $instance;

    public static function getInstance() {
        if (self::$instance== null) {
            self::$instance= new self;
        }
        return self::$instance;
    }

    private function __construct() {
        $this->mem = memcache_connect(...);
    }
}

这实现了一个基本的单例模式。而不是构造对象调用mc::getInstance()。看看单身人士

于 2009-02-15T11:45:36.470 回答
1

您应该使用依赖注入。单例模式和静态结构被认为是不好的做法,因为它们本质上是全局的(并且有充分的理由——它们使您能够使用您实例化的任何类而不是其他类)。

为了便于维护,您应该执行以下操作。

class MemCache {
    protected $memcache;

    public function __construct(){
        $this->memcache = memcache_connect();
    }
}

class Client {
    protected $MemCache;

    public function __construct( MemCache $MemCache ){
        $this->MemCache = $MemCache;
    }

    public function getMemCache(){
        return $this->MemCache;
    }
}

$MemCache = new MemCache();
$Client = new Client($MemCache);
$MemCache1 = $Client->getMemCache();

// $MemCache and $MemCache1 are the same object. 
// memcache_connect() has not been called more than once.
于 2013-08-10T05:14:41.690 回答