抽象单例模式类

抽象单例模式类

问题描述:

I'm trying to achieve the following goal:

Using this general singleton class:

abstract class Singleton {

    private static $instance = null;

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

      return self::$instance;
    }
}

I'd love to be able to create Singleton concrete class such as:

class Registry extends Singleton {
    private function __construct() {}
    ...
}

and then use them as:

Registry::self()->myAwesomePonyRelatedMethod();

But obliviously __CLASS__ is intended as Singleton so a fatal error occurs about PHP not being able to instantiate an abstract class. But the truth is that I want Registry (for example) to be instantiated.

So I tried with get_class($this) but being a static class, Singleton has no $this.

What could I do to make it work?

我正在努力实现以下目标: p>

使用此通用 singleton类: p>

 抽象类Singleton {
 
 private static $ instance = null; 
 
公共静态函数self()
 {
 if(self)  :: $ instance == null)
 {
 $ c = __CLASS __; 
 self :: $ instance = new $ c; 
} 
 
返回self :: $ instance; 
} 
}  
  code>  pre> 
 
 

我希望能够创建Singleton具体类,例如: p>

  class Registry extends Singleton  {
 private function __construct(){} 
 ... 
} 
  code>  pre> 
 
 

然后将它们用作: p> Registry :: self() - > myAwesomePonyRelatedMethod(); code> pre>

但不经意的是 __ CLASS __ code>用作 Singleton code>因此,PHP无法实例化抽象类时会发生致命错误。 但事实是我希望实例化Registry(例如)。 p>

所以我尝试使用 get_class($ this) code>但是作为一个静态类,Singleton没有$ this。 p>

我该怎么做才能使它有效? p> div>

Abridged code from my Slides Singletons in PHP - Why they are bad and how you can eliminate them from your applications:

abstract class Singleton
{
    public static function getInstance()
    {
        return isset(static::$instance)
            ? static::$instance
            : static::$instance = new static();
    }

    final private function __construct()
    {
        static::init();
    }

    final public function __clone() {
        throw new Exception('Not Allowed');
    }

    final public function __wakeup() {
        throw new Exception('Not Allowed');
    }

    protected function init()
    {}
}

Then you can do

class A extends Singleton
{
    protected static $instance;
}

If you need to do additional setup logic override init in the extending class.

Also see Is there a use-case for singletons with database access in PHP?