tags:

views:

55

answers:

3

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?

+2  A: 

I am usingn 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();
echo ( is_a( $oExample1, 'Example' ) && $oExample1 === $oExample2)
? 'Same' : 'Different', "\n"; 
Alexander.Plutov
I thought on this approach, but it has some cons..1. PHP 5.3 is needed2. You class acts as a SingletonContainer3. Derived classes are considered different4. You are calling the constructorBut it has the advantage that you just need to extend that class to have a Singleton
Eridal
A: 

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
A: 

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