#native_company# #native_desc#
#native_cta#

Using the Factory Pattern in PHP Applications Page 2

By Octavia Andreea Anghel
on February 23, 2011

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.