One Step Closer to an Abstract Singleton

The singleton is an incredibly useful pattern in PHP for many reasons. I tend to find myself using them when I know I should be using static classes, but can’t because of PHP’s lack of proper class name discovery in extended static classes. Also, they make great containers for database connections, configuration objects, session wrappers, and anything else that should only live once every page load.

The typical singleton pattern in PHP looks like the following:

<?php class Panda_Singleton {     private $Instance;     private final function __construct()     {}         private final function __clone()     {}     public static function getInstance()     {         if (self::$Instance === null) {             self::$Instance = new self;         }         return self::$Instance;     } } ?>

And that works like a charm every time. The problem is, in one application there may be several classes that need to be singletons. In which case my first thought was to build an abstract singleton. If you have ever tried this, you know my frustration when it didn’t work.

I did however, come up with this:

<?php interface Panda_Singleton_Interface {     public static function getInstance(); } abstract class Panda_Singleton implements Panda_Singleton_Interface {     protected final function __construct()     {}         private final function __clone()     {} } ?>

Which leaves you to implement the $Instance property and the getInstance method. This bugged me because I didn’t want a $Instance floating around in all my concrete classes if I didn’t need to.

Fortunately PHP supports static variables outside of class scope — like in function scope, for example. Or in this case, a class method:

<?php class Foo extends Panda_Singleton {     public static function getInstance()     {         static $Instance;                 if ($Instance === null) {             $Instance = new self;         }                 return $Instance;     } } ?>

That is all that needs to be implemented in concrete classes. Sure, it’s not really much better than what what we were doing before, nor is it any more elegant. But I have found myself using this technique to save a few keystrokes from time to time.

This entry was posted on Saturday, November 24th, 2007 at 10:34 pm and is filed under Code, Design Patterns, PHP. You can leave a response, or trackback from your own site.

One Response to One Step Closer to an Abstract Singleton

developercast.com » Michael Girouard’s Blog: One Step Closer to an Abstract Singleton:

On November 27th, 2007 at 10:45 am #

[...] Girouard has pointed out that things in the PHP world are one step closer to being able to create an abstract Singleton [...]

What do you have to say?

Site Stuff

Pages

Projects

Archives

Categories