HomePHP Page 3 - Creating Objects Dynamically with Factory Methods
Defining a static factory method - PHP
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.
To considerably improve the efficiency of the factory class that you saw in the previous segment, I’m going to perform a two-step changing process: first its factory method will be declared static, and then its “getInstance()” method will be removed, since it won’t be required anymore.
That being explained, please have a look at the modified definition of the factory class:
// define FormElementFactory class
class FormElementFactory
{
public static function factory($formElement, $attributes = array())
{
if ($formElement === 'textbox' or $formElement === 'textarea')
{
return new $formElement($attributes);
}
}
}
See how simple it is to turn the sample factory class into a more compact and useful piece of code? I guess you do! Of course, the class’s enhanced definition shows how its static factory method is capable of easily creating web form element objects, and best of all, without having to deal with any instances of the factory itself.
Naturally, if you’re like me, then you’re eager to see how the improved version of the factory class can be used in a concrete case. With that idea in mind, in the final section of this tutorial I’m going to set up an illustrative example that will show how to utilize the class to create some HTML form element objects.
To learn how this example will be developed, click on the link that appears below and read the upcoming segment.