简体   繁体   中英

Abstract Singleton pattern class

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?

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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM