Abstract Singleton pattern class

2019-04-15 23:50发布

问题:

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?

回答1:

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?