First of all a Singleton is not the same thing as a Simpleton :) although it might be resembled that way in the wide world of Design Patterns.

So like you probably already figured it out, a Singleton is the simplest Design Pattern I can think about. What are Design Pattern you might ask. Well, Design Patterns, as they are called in the IT world, are in fact some sort of “golden eggs” in computer programming. They are reusable solutions to well known problems which you can apply in certain situations. They are field-tested implementations with proven endurance over the years and they are used by a vast majority of our nowadays software applications: websites, standalone applications, multi-server distributed software, you name it…

There are tens or maybe hundreds of well-documented Design Patterns out there, each one of them just waiting to fit your needs. For a quick glimpse you can access the Wikipedia.org page about Design Patterns, and if you like what you see I recommend you to read O’Reilly’s book about Design Patterns called “Head First Design Patterns”.

Anyway, I have two things for you if you’re a novice on Design Patterns:

  • keep your pants on; don’t rush into applying the first design you read about or some exotic design that just seems cool. Not all Design Patterns are fit for every application; that’s why there are so many of them (Design Patterns that is…). So that’s why it’s very important to have a decent knowledge base about this stuff before starting to apply them.
  • don’t get stubborn to apply it like it’s written in the book; feel free to make experiments – Hell, who knows, you might get to be the next guy to come up with a brand new Design Pattern. Too much lecture kills the creativity ;)

Now I hope that you understood at least the two things above, so let’s talk about the Singleton. Like I said, this is one of the easiest out there. It’s actually a creational pattern, because it refers to how certain object are created inside your application and it’s tightly related to the mathematical concept of singleton (aka set with only one unit).

As probably know (or at least you should, otherwise this article is a little bit too advanced for you), in OOP an object is an instance of a predefined class. It inherits the members (properties and methods) of the class it belongs to, BUT it will drastically differ from it’s fellow brothers (objects of the same class) because it’s properties may change at runtime.

So let’s say we have a very complex application with a couple of tens of Models (see MVC, another widely-used pattern), which all need to connect to the DB at some point. Stand a bit and try to imagine what would happen if your MySQL DB would allow you only 500 simultaneous connections and each model will try to connect at the same time to make their tiny job. You might think that 500 simultaneous connection is a something huge which you will never achieve, but let’s say you have 50 models in your design. If I access your website it will probably more than OK. But what if you have a super cool photo on your front page and I send a mass message on Y! Messenger and 20 of my friends will also want to see it in the same time?

What will happen then is that you will exceed your DB capabilities by 100%. And that’s just with 20 simultaneous users.  With 30 users you will exceed them by 200% and so on… Now imagine something like Google or Facebook, which must handle millions of simultaneous users. Algorithms are the cutting edge of technology, much more than hardware, in my opinion.

So here’s how Singleton makes it’s wonderful appearance on the stage. A Singleton is a wonderful little object that each time you call it, wherever you call it from, you are always sure you will always receive the exactly same pack of bits. If every model in the example above would have their own DB connector, you would get in the unwanted and unnecessary situation of exceeding your server’s resources. With Singleton, every model will access the same tiny object, they will all share the same DB connection resource without bothering you (the programmer) with crappy PHP references and making you spend tens or hundreds of hours near Xdebug, not knowing why your PHP5.2.x application eats all the server’s RAM or why once in a while you get a Fatal Error that the memory limit exceeded ;)

So enough with the chit-chatting, let’s see what’s the catch with this fancy Singleton. Building one in PHP has never been simpler. You just have to remember these simple rules:

  • define the constructor as private (and optionally make it final)
  • create a public static method to retrieve the instance you need (the one and only)
  • create a private (or protected) static property where to store the instance that will be returned by the method above

So as you see, a Singleton is a class that will hold it’s own single instance inside a static property and it will serve it to you whenever you will ask for it using a static publicly-accessible method.

And here is a practical example of how to write one in PHP5.x:

class Singleton {
    private static $_instance = null;

    final private function __construct()
    {
    }

    public static function getInstance()
    {
        if (is_null(self::$_instance)) {
            self::$_instance = new Singleton();
        }

        return self::$_instance;
    }
}

Another great implementation of the Singleton Design Pattern is a caching mechanism combined with another very nice pattern called Lazy Loading. Google it!

Also, some other time I will tell you about Singleton’s bigger brother, Multiton.

« »