Singleton

Overview

The singleton pattern is a way to have a single instance of an object shared across an application. Instead of creating a new instance of a class the code asks the class for an instance. If an instance is already created that instance is return otherwise it creates a new instance and returns that one.

Problem

You have a class which contains certain data (i.e., global configuration data) or certain resources (i.e., database connection) and you want to share access to that data across the application without having to create new instances.

Solution

A singleton pattern is the decent way to implement global class instances that can be used by several parts of the code all at once. Usually people will use them for things like loggers, database connections, etc.

/**
 * Singleton class
 */
class Database {
    protected static $instance;

    /**
     * Call this method to get instance of class
     *
     * @return Database
     */
    public static function getInstance() {
        if (self::$instance === null) {
            self::$instance = new Database();
        }
        return self::instance;
    }

    /**
     * Protected constructor so only the class can create its own
     * instances
     */
    private function __construct() {
        // initialization code here
    }
}

// first time called a new database instance is created
$db = Database::getInstance();

// second time called returns previously created instance
$db2 = Database::getInstance();

Don’t Use Singletons

Now that I’ve spent this time teaching you about singletons you shouldn’t ever use them. Singletons are considered bad practice. Following the SOLID Object-Oriented Design singletons introduce code smells. There are cases when you only want one instance of an object but instead of using a singleton pattern you should follow the dependency injection principle and pass the instance around as needed. Here’s a funny little diagram to help you decide when to use singletons (source):

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

About the Author

  • Chris LondonSenior Web ArchitectPartners In Leadership

    I've always worked as an innovative programmer. My insights and creative thinking result in superior products and customer satisfaction. Working full time as a senior web architect I've used lots of exciting technologies (i.e., Ember, Backbone, Handlebars, etc) and developed a lot of exciting sites. In my spare time I hope to develop even more exciting and new technologies. I've been programming professionally for 9 years in everything from desktop applications to web applications to mobile applications.

    Web: https://plus.google.com/116403409191372324375