HomePHP The Singleton and Factory Patterns in PHP: Working With Singletons
The Singleton and Factory Patterns in PHP: Working With Singletons
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.
Welcome to the fourth part of the series “The Singleton and Factory Design Patterns in PHP.” Throughout the previous article, I applied the Factory pattern for implementing an object-oriented method, in order to simplify the creation of regular web forms.
As you remember, in the previous part, I developed a simple form element factory class that handles all of the tasks related to object instantiation. It allows you to define a centralized mechanism within an application for rendering form elements. Certainly, implementing this method makes web form generation a flexible and easy-to-maintain process.
Now that I’ve explained the inherent advantages of applying the Factory pattern to tackle the form developing process, probably you’ll have even more ideas for starting to use design patterns across different applications.
So, returning to this part of the series, the form element factory class was defined as an abstract class. The immediate advantage of having an abstract class rests on using its methods without the concerns related to object instantiation. This means that the functionality of the class is available within the program, but no objects exist to worry about.
However, when we’re working with PHP 4, things are a bit more complex. Unfortunately, PHP 4 doesn’t offer support for abstract classes, although there is a workaround. This presents some difficulties, particularly when a single instance of an object is needed. In the specific case of having a class that instantiates form objects, it’s highly desirable to work with a single instance of it, instead of dealing with multiple and resource-consuming instances.
Over the next few lines, I’ll explain the process for making the form element factory class a Singleton. This will help you to easily avoid multiple object instantiation issues, specifically when working on a PHP 4 development platform. Now that we have the theory well under the way, let’s get started.