Home arrow PHP arrow 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.

  1. Creating Objects Dynamically with Factory Methods
  2. Review: implementing the Singleton pattern inside a factory class
  3. Defining a static factory method
  4. Calling a factory method out of the object scope
By: Alejandro Gervasio
Rating: starstarstarstarstar / 1
December 07, 2009

print this article



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.

>>> 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: