题
我有用于与内存缓存服务器交互的一类。我对插入,删除和检索数据不同的功能。最初为每个功能进行的呼叫到memcache_connect()
,然而这是不必要的,e.g:
mc->insert()
mc->get()
mc->delete()
将使3个内存缓存连接。我工作围绕这通过创建该类的构建体:
function __construct() {
$this->mem = memcache_connect( ... );
}
和然后使用$this->mem
哪里需要的资源,所以每个的三个功能使用相同的资源memcache_connect
这是正常的,但是,如果我打电话其它类内的类,e.g:
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
。
有没有办法做到这一点,或者我应该只使用全局?
解决方案
我会使用单件模式用于获取内存缓存的唯一实例代码中的另一个类。这样的 -
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, ...)
...
其他提示
传递在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);
等
我想你要找的静态属性在这里。
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()
。看看单身。
您应该使用依赖注入。 Singleton模式和静态结构被认为是不好的做法,因为他们基本上都是全局变量。(有很好的理由 - 他们巩固您在使用实例化任何类,而不是其他一些)
下面是一样的东西,你应该为了做有维修方便。
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.
不隶属于 StackOverflow