Working with CSS Styles and the Stage Pattern in PHP 5 - Completing the implementation of the stage pattern (
Page 4 of 4 )
Indeed, the best way to understand how the stage pattern works with this specific implementation is by creating a functional example that demonstrates how a given web document can use different CSS styles according to specific format requirements.
In this case, the following sample pair of scripts show how an instance of the contextual "CSScontext" class is capable of modifying the behavior of a specific "WebPage" object to generate two different versions of the same web document.
Now that I have explained how the pertinent example is going to work, please examine the corresponding source code, which looks like this:
// example displaying a normal web page
try{
// create new 'CSSContext' object
$cssContext=new CSSContext();
// set CSS styles to work with a normal web page format
$cssContext->setPageFormat('normal');
// create new 'WebPage' object
$webPage=new WebPage($cssContext->getCSS());
$webPage->makeHeader();
$webPage->makeBody();
$webPage->makeFooter();
// display web page using normal format
echo $webPage->getHTML();
}
catch(Exception $e){
echo $e->getMessage();
exit();
}
// example displaying a printer-friendly web page
try{
// create new 'CSSContext' object
$cssContext=new CSSContext();
// set CSS styles to work with a printer-friendly web page
format
$cssContext->setPageFormat('print');
$webPage=new WebPage($cssContext->getCSS());
$webPage->makeHeader();
$webPage->makeBody();
$webPage->makeFooter();
// display web page using printer-friendly format
echo $webPage->getHTML();
}
catch(Exception $e){
echo $e->getMessage();
exit();
}
As shown above, the stage pattern is implemented here to change the behavior of a "WebPage" object so it can display distinct versions of the same web document. As you can see in the two previous scripts, the first time the web page is rendered, a "normal" CSS style is used, while in the second case, the page in question is displayed with a "printer-friendly" format.
At this point, I believe that the previous code samples should give you an accurate idea of how to implement the stage pattern in a concrete situation. However, as with many other design patterns, I suggest you create your own testing examples to acquire a better grounding in how it this pattern functions.
Final thoughts
Unfortunately, we've come to the end of this journey. In these two tutorials, I introduced the basic concepts of the stage pattern, and also showed you a couple of functional examples where it can be applied with minor hassles.
As you hopefully learned, if you ever need to build a class that changes the way it works according to the modifications introduced into its context, the stage pattern can provide a good method for solving this issue.
See you in the next PHP tutorial!