Home arrow PHP arrow Page 2 - The Singleton and Factory Patterns in PHP: Working With Singletons

Working with a single object instance: making the “formElementFactory” class a Singleton - PHP

In this fourth part of the series covering the Singleton and Factory Design Patterns in PHP, we will discuss issues stemming from the fact that PHP 4 does not have an abstract class. Since we found it useful in the previous article to define the form element factory class as an abstract class, in this article we will discuss the process for making the form element factory class a Singleton, and how this serves our purposes.

  1. The Singleton and Factory Patterns in PHP: Working With Singletons
  2. Working with a single object instance: making the “formElementFactory” class a Singleton
  3. The previous step: defining form element classes in PHP4
  4. Ending up the coding round: defining the remaining form element classes
By: Alejandro Gervasio
Rating: starstarstarstarstar / 5
November 30, 2005

print this article



A good place to start turning the form element factory class into a Singleton is by taking a look at its definition for use in PHP5. As you hopefully remember, the class looks like this:

abstract class formElementFactory{
    private function __construct(){}
    public static function createElement($type,$attributes=array()){
            throw new Exception('Invalid method parameters');
        // instantiate a new form element object
        $formElement=new $type($attributes);
        // return form object’s HTML
        return $formElement->getHTML();

As I mentioned before, the class is defined as abstract, and presents a single functional method, “createElement()”, which carries out the instantiation of form objects, as well as the implementation of Polymorphism. It does this through the “getHTML()” method, which is useful for returning the proper (X)HTML code for each form element.

A possible use of the class would be the following, assuming that form element classes have already been defined:

// make array with parameters to be passed to the class


foreach($formElements as $element=>$attributes){

    // display form elements

    echo formElementFactory::createElement($element,$attributes).'<br />';


Through the above lines of code, we first created a few form objects, and then displayed their HTML code, by using a “foreach” loop. Although basic, the example reveals the strengths of the factory class, since rendering form elements becomes an extremely easy process.

As you can see, working with an abstract class in PHP5 is straightforward. However, when programming in PHP 4, things are a bit more messy. This is particularly true if we’re working with a form factory class, while a single instance of it is needed. Using references may certainly help, due to the fact that we’re not spawning multiple copies of an object. When building large applications, however, tracking the existence of an object can sometimes be a cumbersome task.

There’s a better approach to solving this issue. By applying the Singleton pattern, we can make sure that only a single instance of the factory class is available across the program, and other objects are using this unique instance. Based on this concept, making the class a Singleton is as simple as this:

class formElementFactory{
    function formElementFactory(){}
    function getInstance(){
            static $instance;
                $object= __CLASS__;
                $instance=new $object;
            return $instance;
    function createElement($type,$attributes=array()){
            trigger_error('Invalid method
        // return a new form element object
        return new $type($attributes);

Let’s analyze the Singleton version of the class. Notice the existence of the same “createElement()” method that returns a new form object, according to the type of input passed to it, which is identical to the PHP5 incarnation. Until now, we've seen nothing unexpected. However, there’s another relevant method, “getInstance()” that makes sure that only a single instance of the object is always returned.

By declaring a static $instance variable, we’re ensuring that once an instance of the object has been created, no additional instances will exist. Just in case you’re not aware of this: when a static variable is defined as static within a function scope, it won’t lose its value, even if the program has left this scope.

Therefore, because of the static type of the $instance variable, the following expression:

      $object= __CLASS__;
      $instance=new $object;
  return $instance;

always returns a single instance of the object. As a result, a Singleton version of the factory class has been defined. Considering this, whenever a PHP program creates an object belonging to the class, a unique instance will be available within its execution.

Perhaps the implementation of the Singleton pattern is a little harder to understand. Definitely, the concept will be  understood best by taking a look at some examples. Join me in the next explanation to see how a Singleton class can work along with some form element classes.

>>> More PHP Articles          >>> More By Alejandro Gervasio

blog comments powered by Disqus
escort Bursa Bursa escort Antalya eskort


- Hackers Compromise PHP Sites to Launch Attac...
- Red Hat, Zend Form OpenShift PaaS Alliance
- PHP IDE News
- BCD, Zend Extend PHP Partnership
- PHP FAQ Highlight
- PHP Creator Didn't Set Out to Create a Langu...
- PHP Trends Revealed in Zend Study
- PHP: Best Methods for Running Scheduled Jobs
- PHP Array Functions: array_change_key_case
- PHP array_combine Function
- PHP array_chunk Function
- PHP Closures as View Helpers: Lazy-Loading F...
- Using PHP Closures as View Helpers
- PHP File and Operating System Program Execut...
- PHP: Effects of Wrapping Code in Class Const...

Developer Shed Affiliates


Dev Shed Tutorial Topics: