HomePHP Page 5 - Building a Web Page Controller for Simulating the Model-View-Controller Schema in PHP
Putting the MVC schema to work: generating style sheets on the fly - PHP
If you’re one of those PHP developers that want to extend your background in object-based applications, then this series might be quite attractive to you. In these three tutorials (of which this is the second), you’ll learn how to simulate a simple Model-View-Controller schema, which can be easily expanded to construct more complex relationships between the different entities, in this case applicable specifically to PHP classes.
In order to demonstrate how the MVC schema can be used to attach different style sheets to the web page created by the respective “WebPage” class, first I’ll define three sample style files. As you’ll see, these styles will be displayed dynamically, based on the instructions given originally by the "PageController" class.
In consonance with the concepts that I deployed before, here are the respective definitions of the three sample CSS files:
All right, after defining the three CSS files that you saw before, take a look at the following example, which uses the first style file, and then renders the web page in question:
// display web page with the first style sheet try{ $pageController=new PageController('styles1'); $webPage=new WebPage($pageController); $webPage->doHeader(); $webPage->doBody(); $webPage->doFooter(); $styleGenerator=new StyleGenerator($webPage); echo $styleGenerator->generateStyle(); } catch(Exception $e){ echo $e->getMessage(); exit(); }
As you can see, the above script shows how the “PageController” object determines what style sheet to use when rendering the corresponding web page. The result of this code snippet can be appreciated in the screen shot below:
Similarly, the other two style sheets can be attached to the web document as shown below:
// display web page with the second style sheet try{ $pageController=new PageController('styles2'); $webPage=new WebPage($pageController); $webPage->doHeader(); $webPage->doBody(); $webPage->doFooter(); $styleGenerator=new StyleGenerator($webPage); echo $styleGenerator->generateStyle(); } catch(Exception $e){ echo $e->getMessage(); exit(); }
Definitely, you’ll have to agree with me that this simple MVC schema really works. Try creating more style sheets and see what happens in each case. The experience is really worthwhile!
Final thoughts
Unfortunately, we’re finished now. Over this second part of this series, I demonstrated how to implement the Model-View-Controller schema with PHP, by setting up a simple example that shows how to attach different style sheets to a given web document, based on the instructions given by a page controller.
If this example wasn’t enough for you, there’s still more material to learn. In the last tutorial, I’ll show you how to use an MVC-based object relationship to produce disparate outputs from returned MySQL result sets. See you in the last part!