HomePHP Creating Objects Dynamically with Factory Methods
Creating Objects Dynamically with Factory Methods
Welcome to the third part of a series that shows you how to implement factory methods in PHP 5. Made up of six tutorials, this series uses numerous friendly code samples to illustrate how to implement the Factory and Singleton design patterns within your PHP 5-based web applications. In this way, they will be able to build objects in a truly efficient manner.
And now that you know what to expect from this set of articles, itís time to review the topics that were discussed in the last one. In that installment of the series, I explained how to build a simple factory class that could return to client code objects that represented a couple of common web form elements, including input text boxes and text areas.
Naturally, these objects were created by a basic factory method, which was always called in the object context, that is, dynamically. However, the most relevant aspect to note with reference to the way that this factory class was defined was the existence of a static method called ďgetInstance(),Ē which returned Singletons of the class in question.
Also, itís worth mentioning that the implementation of this static method followed a simple, important rule: it did not deal with multiple instances of the factory class within a given script. Even though this approach does permit you to work with a unique instance of the mentioned class, it can be improved even further.
But how can this be done? Well, as a rule of thumb, classes that create an instance of themselves should implement a static factory method that returns Singletons, while factory classes that spawn other objects should have only a static factory method.
The form element factory class created in the previous article falls under this last category. Therefore, in the next few lines Iím going to change the declaration of its factory method to make it static. This way, no instance of this class will be required to create form element objects.
If this explanation sounds rather confusing to you, then dissipate that cloud of doubt and begin reading now!