4

I want to define a Singleton base type from which the user will derive his classes, so this is what I thought:


interface SingletonInterface {
    public static function getInstance();
}

abstract class SingletonAbstract implements SingletonInterface {
    abstract protected function __construct();
    final private function __clone() {}
}

But using this aproach the user may implement this singleton...


class BadImpl implements SingletonInterface {
    public static function getInstance() {
        return new self;
    }
}

What would be your aproach?

eridal
  • 1,288
  • 1
  • 11
  • 23
  • *(related)* [What is so bad about Singletons](http://stackoverflow.com/questions/137975/what-is-so-bad-about-singletons) – Gordon Aug 19 '10 at 06:51

4 Answers4

3

Remember PHP doesn't allow multiple inheritance so you must carefully choose what you base your classes on. Singleton is so easy to implement it's probably better to let each class define it. Beware also that private fields are not ported to descendant classes and therefore you can have two different fields with the same name.

greg
  • 696
  • 1
  • 9
  • 16
2

I am using this code for creating a Singleton:

abstract class Singleton {

    private static $_aInstance = array();


    private function __construct() {}

    public static function getInstance() {

       $sClassName = get_called_class(); 

       if( !isset( self::$_aInstance[ $sClassName ] ) ) {

          self::$_aInstance[ $sClassName ] = new $sClassName();
       }
       $oInstance = self::$_aInstance[ $sClassName ];

       return $oInstance;
    }

    final private function __clone() {}
}

This is using of this pattern:

class Example extends Singleton {
   ...
}

$oExample1 = Example::getInstance();
$oExample2 = Example::getInstance();

if(is_a( $oExample1, 'Example' ) && $oExample1 === $oExample2){

    echo 'Same';

} else {

    echo 'Different';
}
TarranJones
  • 4,084
  • 2
  • 38
  • 55
Alex Pliutau
  • 21,392
  • 27
  • 113
  • 143
  • I thought on this approach, but it has some cons.. 1. PHP 5.3 is needed 2. You class acts as a SingletonContainer 3. Derived classes are considered different 4. You are calling the constructor But it has the advantage that you just need to extend that class to have a Singleton – eridal Aug 19 '10 at 13:59
0

You can now use traits, but do you need so much singletons ?

Webaaz
  • 11
  • 2
0

First of all: if you have so much Singletons over the project then you probably mess up something on projection level

Second of all: Singleton should be used there, and only there, where more that one instance of a class makes totally no sense or might cause some errors

Finally: the inheritance ain't designed to reduce the amount of code

Crozin
  • 43,890
  • 13
  • 88
  • 135