Home arrow PHP arrow Page 2 - Creating Objects Dynamically with Factory Methods

Review: implementing the Singleton pattern inside a factory class - 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.

TABLE OF CONTENTS:
  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
SEARCH DEV SHED

TOOLS YOU CAN USE

advertisement

Before I start explaining how to change the definition of the factory class built in the preceding tutorial to make its factory method static, I'd like to review how this class could be used in its original state to create a pair of web form element objects very quickly.

That being said, here are the definitions corresponding to the classes that render those web form elements. Look at them, please:

// define TextBox class

class TextBox

{

private $name = 'mytextbox';

private $id = 'textbox';

private $class = 'textbox';

private $maxlength = 20;

 

// constructor

public function __construct($attributes = array())

{

if (empty($attributes) === FALSE)

{

foreach ($attributes as $attribute => $value)

{

if (in_array($attribute, array('name', 'id', 'class', 'maxlength')) and empty($value) === FALSE)

{

$this->$attribute = $value;

}

}

}

}

 

// renders input text box element

public function render()

{

return '<input type="text" name="' . $this->name . '" id="' . $this->id . '" class="' . $this->class . '" maxlength="' . $this->maxlength . '" />';

}

}

 

 

// define TextArea class

class TextArea

{

private $name = 'mytextarea';

private $id = 'textarea';

private $class = 'textarea';

private $rows = 10;

private $cols = 20;

 

// constructor

public function __construct($attributes = array())

{

if (empty($attributes) === FALSE)

{

foreach ($attributes as $attribute => $value)

{

if (in_array($attribute, array('name', 'id', 'class', 'rows', 'cols')) and empty($value) === FALSE)

{

$this->$attribute = $value;

}

}

}

}

 

// renders textarea element

public function render()

{

return '<textarea name="' . $this->name . '" id="' . $this->id . '" class="' . $this->class . '" rows="' . $this->rows . '" cols="' . $this->cols . '"></textarea>';

}

}

Undeniably, understanding the driving logic of the two classes above should be a straightforward process for you. All they do is return via their “render()” public method the markup required to display on screen some input text boxes and text areas, in accordance with the arguments passed to their constructors. Period.

Moving forward, it’s time to show the definition of the factory class, which returns to client code instances of the previous classes. In addition, it’s valid to notice that this factory class implements a static “getInstance()” method, which simply returns Singletons of that class.

Here’s how this sample class looks:

class FormElementFactory

{

private static $instance = NULL;

 

// get Singleton instance of form element factory class

public static function getInstance()

{

if (self::$instance === NULL)

{

self::$instance = new FormElementFactory;

}

return self::$instance;

}

public function factory($formElement, $attributes = array())

{

if ($formElement === 'textbox' or $formElement === 'textarea')

{

return new $formElement($attributes);

 }

}

}

As seen above, the “factory()” method defined within the previous class is tasked with spawning HTML form element objects, while its “getInstance()” static method is responsible for returning only one instance of the class. Simple to code and read, right?

So far, so good. Having shown you the definitions corresponding to all of these sample classes, it’s time to set up an example that puts them to work together. So, here’s a simple script that does exactly that. Pay close attention to it:

// create instance of FormElementFactory class using its 'getInstance()' method

$formFactory = FormElementFactory::getInstance();

// create some form elements objects

$texBox = $formFactory->factory('textbox');

$textArea = $formFactory->factory('textarea');

// display form elements

echo $texBox->render() . '<br />' . $textArea->render();

There you have it. As this script shows, it’s extremely easy to take advantage of the functionality provided by the factory class to create a couple of web form element objects. Finally, once those objects are brought into existence, displaying their markup is only a matter of calling their “render()” method and nothing else.

However, not everything looks good in this example, unfortunately. To spawn the corresponding web form element objects, at least one single instance of the factory class had to be created. This necessity can be avoided easily by calling its “factory()” method out of the object context.

To do things the right way, however, the method in question should be declared static too. So, in the next section I’m going to introduce this small change into the definition of the pertinent factory class, thus making its factory method much more efficient.

To learn more on this updating process, read the following segment. It’s only one click away.



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

blog comments powered by Disqus
escort Bursa Bursa escort Antalya eskort
   

PHP ARTICLES

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