views:

279

answers:

3

I am working on a simple abstract database class. In my usage of this class, I'll want to have some instance be a singleton. I was thinking of having a abstract class that is not a singleton, and then extend it into another abstract class that is a singleton. Is this possible? Recommended?


Edit: I want to have two abstract that are practically identical, except one is a singleton. So the only difference will be that one will have all the functions of the other, but will have the other properties and methods that make it behave like a singleton.

I'd like to have one base class code base for this so as I make changes, I don't have to keep two files in sync.

A: 

Abstract Singletons will work from 5.3 only due to Late Static Binding. See the code at http://www.phpbar.de/w/Abstract_Singleton for an implementation.

You can do

abstract class Singleton{ 
    // includes the Singleton code and nothing else
}

abstract class Foo extends Singleton { 
    // includes the methods Foo should be responsible for
}

class Bar extends Foo {
    // includes specialized code only applicable to Bar
}

but keep in mind the second you put an abstract method into Singleton or Foo, they will stop working until you implement them at some level in the class hierarchy:

When inheriting from an abstract class, all methods marked abstract in the parent's class declaration must be defined by the child;

From: http://uk.php.net/manual/en/language.oop5.abstract.php

Gordon
I want to have two abstract that are more or less identical, except one is a singleton.
A: 

The implementation of the singleton pattern must satisfy two requirements:

  1. It must provide a mechanism to access the singleton class instance without creating a class object
  2. It must persist the singleton object so that it is not instantiated more than once

As long as that's provided, the variations are multiple. There's nothing wrong with making the class abstract extending from another abstract, if that's what you need. BUT, as @Gordon says, be aware that overriding static methods/properties causes peculiar behaviours in PHP < 5.3.

nuqqsa
+1  A: 

In the way that I do things, I believe that there's no use for an abstract singleton. This is because,

1) What you want to be a singleton is the final class you instantiate for use within the application whether it'd be a library, model, controller or view and NOT the abstract.

2) Adding the singleton method is easy and can be written in 8 lines. See below.

protected static $_instance;
public static function getInstance()
{
    if (!isset(self::$_instance)) {
        self::$_instance = new self();
    }
    self::$_instance;
}

3) PHP 5.3 below version doesn't support late static binding. This will result in instantiating the abstract class instead of the final class inheriting it and will not function as expected, as already mentioned by Gordon and nuqqsa. So, for backward compatibility, better avoid it.

walkthroughthecloud