In this article you will learn how to use the factory pattern design in your PHP application to construct different objects for interrogating a database (books) and displaying the records from a table (bookstore). You'll also learn how to display a randomized array of strings and colors, and how to display a randomized array of strings and some associated pictures into an HTML table.
The essence of the factory method pattern is to "define an interface for creating an object, but let the subclasses decide which class to instantiate. The Factory method lets a class defer instantiation to subclasses." (source: Wikipedia).
The factory pattern is a design pattern which is used in software development to encapsulate the processes used for creating objects. The factory pattern also allows for the instantiation of objects at runtime, as you will see in the below applications of this article. It is called a Factory Pattern because it is responsible for "manufacturing" an object -- you'll also see this below.
A factory method has a distinct name. In principle, a factory pattern can be used when: the creation of the object precludes reuse without significantly duplicating code, the creation of the object requires access to information or resources not appropriate to contain within the composing object, the lifetime management of created objects needs to be centralized to ensure consistent behavior.

Factory Pattern Method for PHP User Login Application

The polymorphism mechanism and the use of base class is really the center of OOP, but at some level, a concrete instance of the base class's subclasses should be created. This is usually done using the factory pattern; a Factory class has a static method which receives some input and according to that input, it decides what class instance to create (usually a subclass).
Factory classes are useful when you need a complicated process for constructing the object, when the construction needs a dependency that you do not want for the actual class, and when you need to construct different objects.
To better understand when the factory pattern should be used, let's take a real example. Suppose that on a website, different kinds of users can log in. Some are guests, some are regular customers, and others are administrators. Normally, you would have a base class User and have three subclasses: GuestUser, CustomerUser , and AdminUser . The base class, User, and its subclasses would contain methods that give information about the user (for example, permissions on what they can access on the website and their personal preferences). So, this is the moment when the factory pattern design pattern gets involved: the elegant way for you to write your Web application is to use the base class User as much as possible, so that the code would be generic and that it would be easy to add additional kinds of users when the need arises.
In the first application of this article you will see how the polymorphism mechanism works using two classes, RandomMessage and messageCreator. The base class is RandomMessage and the factory class is messageCreator. As you may notice, the messageCreator factory class contains the createMessage method which returns a new instance of the RandomMessage class. To output the result you should create an instance of the factory method, messageCreator, and use the getMessage and getColor from the base class, RandomMessage, to list the results.
Below you can see the listing and its result:
//Creating the RandomMessage class containing a function to randomize the 

//messages and colors arrays and two functions that returns the results class RandomMessage { var $messages; var $colors; function RandomMessage() { // Declaring the array of messages $this->messages=array( 'This is a factory pattern application!', 'The first application of this article!' ); // Declaring the array of colors $this->colors=array( '#FF33CC','#D6008F' ); // Shuffle the messages srand ((float)microtime()*1000000); shuffle ($this->messages); // Shuffle the colors srand ((float)microtime()*1000000); shuffle ($this->colors); } //Return the randomized message function getMessage() { return $this->messages[0]; } //Return the randomize color function getColor() { return $this->colors[0]; } } //Defining the factory class that contains the factory method class messageCreator { // The factory method... function & createMessage () { // Return a new instance of RandomMessage class return new RandomMessage(); } } //Creating an instance of the factory method, messageCreator, from above $messageMaker=new messageCreator; //Outputs the result for ( $i=0; $i<5; $i++ ) { $randomMessage=& $messageMaker->createMessage(); $color = $randomMessage->getColor(); echo ( ''.$randomMessage-> getMessage().' ' ); } ?>
Two of the result outputs of the above application are listed below:

 

This is a factory pattern application!
The first application of this article!
This is a factory pattern application!
The first application of this article!
The first application of this article!

 

This is a factory pattern application!
This is a factory pattern application!
This is a factory pattern application!
The first application of this article!
This is a factory pattern application!

 

You may notice that not only the messages are randomized but also the colors.

Factory Pattern Method for PHP Randomized Result Application

The next application looks like the above one, but the result will be an HTML table containing randomized flowers and their corresponding picture. You may notice that, in this application, the base class is flower and the factory class is FlowersFactory, which contains the makeFlower method listed below:
function & makeFlower () {
// Return a new instance of RandomMessage
return new flower();
}
Next, you can see the flower.php application listed below:
echo "";
echo "";
echo "";
echo "";
echo "
FLOWERS
";
//defining the base class
class flower {
var $flowers;
function flower() {
// An array of messages
$this->flowers=array(
'Tulips','Roses', 'Lilies'
);
// Shuffle the messages
srand ((float)microtime()*1000000);
shuffle ($this->flowers);
}
function getMessage() {
return $this->flowers[0];
}
}
//defining the factory class
class FlowersFactory {
// The factory method…
function & makeFlower () {
// Return a new instance of RandomMessage
return new flower();
}
}
//Creating an instance of the factory method, FlowersFactory, from above
$flowersFactory=new flowersFactory;
//Outputs the result 
for ( $i=0; $i<5; $i++ ) {
$randomFlower=& $flowersFactory->makeFlower();
echo ( $randomFlower->getMessage().' ' );
$picture = $randomFlower->getMessage();
echo ' ';
}
echo "";
echo "";
?>
Two different outputs of the above listing are:


Click here for larger image

Figure 1. First Output of the flower.php Application Using the Factory Pattern Method


Click here for larger image

Figure 2. Second Output of the flower.php Application Using the Factory Pattern Method
The next application is a little more complicated than the other two and consists in interrogating the books database and its table, bookstore, created using the following SQL statements:
insert into bookstore values (1,'PHP and MySQL','Welling Thomson','234-2445-1234','23$')
insert into bookstore values (2,'PHP5','Addison Wesley','189-210-123','19$')
insert into bookstore values (3,'JavaServerPages','SAMS','355-677-888','31$')
insert into bookstore values (4,'Visual Basic.net','JAMSA','611-115-564','26$')
insert into bookstore values (5,'JBoss Tools 3','Anghel Leonard','433-366-564','39$')
Below is a print screen image of the bookstore table:


Click here for larger image

Figure 3. The Bookstore Table Structure and Content Used in the database.php Application to Show the Factory Pattern Mechanism
The below application consist of two classes, Articles and Article. The first class extracts the articles from the books database and stores the results into the articles array. The Article class is built by the factory method, getArticle, and returns all the records: id, book, author, isbn, price content, one at time.
The database.php application is listed below:
// Fetches a list of articles from a database
class Articles {

var $articles;

function Articles ( &$dbConn ) { 
// Pull the articles from the database
$sql="SELECT * FROM bookstore";
$result = $dbConn->query($sql);

// Storing the articles into the articles array
while ( $row = mysqli_fetch_array($result) ) {
$this->articles[]=$row;
}
}

// Factory method creates new instances of Article
function & getArticle () { 

foreach ($this->articles as $row){ 
$instance[] = new Article($row); 
}

return $instance; 
} 
}

// The Article class is built by the factory method
class Article {
var $id;
var $book;
var $author;
var $isbn;
var $price;

function Article($data) {

$this->id=$data['id']; 
$this->book=$data['book'];
$this->author=$data['author'];
$this->isbn=$data['isbn'];
$this->price=$data['price'];

}

function id() {
return htmlspecialchars($this->id);
}

function book() {
return htmlspecialchars($this->book);
}

function author() {
return htmlspecialchars($this->author);
}

function isbn() {
return htmlspecialchars($this->isbn);
}

function price() {
return htmlspecialchars($this->price);
}

}

const MYSQL_HOST = "127.0.0.1";
const MYSQL_USER = "";
const MYSQL_PASS = "";
const MYSQL_DB = "books";

//Connecting to MySQL
$dbConn = new MySQLi(MYSQL_HOST,MYSQL_USER,MYSQL_PASS,MYSQL_DB);
if($dbConn->connect_error)
{
throw new Exception('MySQL connection failed: ' . $dbConn-> connect_error);
} else {
//creating an instance of the Articles class
$dbarticles=new Articles($dbConn);

// The factory method is used here
$articleInstances=$dbarticles->getArticle();

//Outputs each record fields
foreach ($articleInstances as $article){
echo ( "
".$article->id()."
________________________________________
" ); 
echo ( "".$article->book()."
" ); 
echo ( "".$article->author()."
" ); 
echo ( "".$article->isbn()."
" ); 
echo ( "".$article->price()."
" ); 
}
}

//Close the connection
mysql_close($dbConn);

?>
The output of the database.php application is listed below:

// Fetches a list of articles from a database

class Articles {

 

var $articles;

 

function Articles ( &$dbConn ) {

// Pull the articles from the database

$sql="SELECT * FROM bookstore";

$result = $dbConn->query($sql);

 

// Storing the articles into the articles array

while ( $row = mysqli_fetch_array($result) ) {

$this->articles[]=$row;

}

}

 

// Factory method creates new instances of Article

function & getArticle () {

 

foreach ($this->articles as $row){

$instance[] = new Article($row);

}

 

return $instance;

}

}

 

// The Article class is built by the factory method

class Article {

var $id;

var $book;

var $author;

var $isbn;

var $price;

 

function Article($data) {

 

$this->id=$data['id'];

$this->book=$data['book'];

$this->author=$data['author'];

$this->isbn=$data['isbn'];

$this->price=$data['price'];

 

}

 

function id() {

return htmlspecialchars($this->id);

}

 

function book() {

return htmlspecialchars($this->book);

}

 

function author() {

return htmlspecialchars($this->author);

}

 

function isbn() {

return htmlspecialchars($this->isbn);

}

 

function price() {

return htmlspecialchars($this->price);

}

 

}

 

const MYSQL_HOST = "127.0.0.1";

const MYSQL_USER = "";

const MYSQL_PASS = "";

const MYSQL_DB = "books";

 

//Connecting to MySQL

$dbConn = new MySQLi(MYSQL_HOST,MYSQL_USER,MYSQL_PASS,MYSQL_DB);

if($dbConn->connect_error)

{

throw new Exception('MySQL connection failed: ' . $dbConn-> connect_error);

} else {

//creating an instance of the Articles class

$dbarticles=new Articles($dbConn);

 

// The factory method is used here

$articleInstances=$dbarticles->getArticle();

 

//Outputs each record fields

foreach ($articleInstances as $article){

echo ( "

".$article->id()."


" );

 

echo ( "".$article->book()."
" );

echo ( "".$article->author()."
" );

echo ( "".$article->isbn()."
" );

echo ( "".$article->price()."
" );

}

}

 

//Close the connection

mysql_close($dbConn);

 

?>

The output of the database.php application is listed below:

1


PHP and MySQL
Welling Thomson
234-2445-1234
23$

2


PHP5
Addison Wesley
189-210-123
19$

3


JavaserverPages
SAMS
355-677-888
31$

4


Visual Basic.net
JAMSA
611-115-564
26$

5


JBoss Tools 3
Anghel Leonard
433-366-564
39$

 

Conclusion

The factory pattern can be really useful when you need to create multiple objects that belong to the same family.

About the Author

Octavia Andreea Anghel is a senior PHP developer currently working as a primary trainer for programming teams that participate at national and international software-development contests. She consults on developing educational projects at a national level. She is a coauthor of the book "XML Technologies: XML in Java" (Albastra, ISBN 978-973-650-210-1), for which she wrote the XML portions. In addition to PHP and XML, she's interested in software architecture, web services, UML, and high-performance unit tests. to e-mail her.