Factoring Content Boxes with the Factory Pattern in PHP 5 - Displaying web page content boxes via the factory pattern (
Page 4 of 4 )
As I explained in the previous section, a good method for demonstrating how the factory class that I defined in the beginning of this tutorial can be used to display distinct types of content boxes is to develop a fully-functional example where a sample web page is constructed and the boxes are included in its main section.
Based on this premise, below I coded a short script which performs these tasks.
Please look at the following code sample:
try{
// create new web page object
$webPage=new WebPage();
// display web page header
echo $webPage->createHeader();
// create some content boxes
$greyBox=ContentBoxFactory::createContentBox('grey','Title for
grey box','This is the sample content for a grey box that has
been created with the factory pattern.');
$blueBox=ContentBoxFactory::createContentBox('blue','Title for
blue box','This is the sample content for a blue box that has
been created with the factory pattern.');
$yellowBox=ContentBoxFactory::createContentBox('yellow','Title
for yellow box','This is the sample content for a yellow box that
has been created with the factory pattern.');
// display content boxes
echo $greyBox->display();
echo $blueBox->display();
echo $yellowBox->display();
// display web page footer
echo $webPage->createFooter();
}
catch(Exception $e){
echo $e->getMessage();
exit();
}
It may be hard to believe, but the above script is all the source code required to display a sample web document that contains the three previously defined content boxes. In this case, I used the corresponding factory class to generate each of the content box objects, which are displayed on the web page via their "display()" method.
As you can see, this is a fine demonstration of how to use the neat functionality provided by the factory pattern in a real world situation. So, do you want to put this helpful pattern to work? Go ahead and try developing your own examples!
Final thoughts
Sadly, we've come to the end of this series. In these three articles, I showed you with numerous examples how to implement the factory design pattern with PHP 5. Hopefully, this series will contribute to expand your existing background in pattern-based programming.
See you in the next PHP tutorial!