Building a Web Page Controller for Simulating the Model-View-Controller Schema in 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.

Introduction

Stepping back for a moment to the first tutorial of the series, you’ll certainly remember some of the topics that I discussed before. First of all, I went through the basic concepts of how to define and implement an MVC (Model-View-Controller) relationship between classes, by developing a simple and practical example.

As you’ll surely recall, this example consisted basically of three separated classes, where each one was originally defined to fit the requirements of a highly-generic MVC schema. In this case, the first class was built as a basic message controller class, then the second one (the model) was constructed to behave like a simple message saving mechanism, and lastly the third one was responsible for generating different views (lowercase, uppercase and reversed, respectively) from an input string passed as an argument to the controller class.

Of course, it’s not my intention here to develop a full-featured MVC schema like the one used in Ruby on Rails, but instead provide you with an easy-going introduction to simulating this relationship by the means of some concrete PHP classes. From that point onward, you can expand the model, and develop more sophisticated applications.

Well, assuming that this introduction has refreshed most of the concepts deployed in the previous tutorial, the next step on this journey consists of implementing the MVC schema in the context of a real-world application. We’re going to build a web page controller system, which will be capable of creating different style sheets on the fly. In this way it will generate several views from the same model, that is the web document in question.

The experience will be really educational, therefore let’s continue learning how to implement a more realistic MVC relationship with PHP. Let’s get going!

{mospagebreak title=Creating the first component of the schema: defining a web page controller class}

Since I plan to follow a logical sequence for building this new MVC schema with PHP, first I’ll define the controller itself, which in this case is represented by a simple web page controller class.

As you’ll learn later on, this class will be responsible for instructing the model about what style sheet should be used when rendering the corresponding web document. But, in fact, I’m getting ahead of myself, so now pay attention to the definition of this controller class, which is listed below:

// define ‘PageController’ class (controller)
class PageController{
    private $styleRanges=array(‘styles1′,’styles2′,’styles3′);
    private $style;
    public function __construct($style=’styles1′){
        if(!in_array($style,$this->styleRanges)){
            throw new Exception(‘Invalid web page style!’);
        }
        $this->style=$style;
    }
    // return type of view
    public function getStyle(){
        return $this->style;
    }
}

As shown above, the “PageController” class accepts the name of a specific style sheet as the only incoming argument, in order to assign it as a property inside the respective constructor. Of course, it’s easy to guess that this style will be used by the controller class to instruct the web document on what style sheet to display, by using the “getStyle()” method defined above.

Still with me? Fine, now that you know how the web page controller class looks, let me walk one step further and show you the second link of the MVC schema. In the next section of the article, you’ll see how to build a simple –- yet efficient — web page generator class, which will represent the model element inside the MVC relationship that I’m currently developing.

To learn more about how this class will be defined, please click on the link that appears below and keep on reading.

{mospagebreak title=Creating a real-world model: defining a web page generator class}

As I expressed a few lines above, once the corresponding web page generator class has been defined, logically the next step rests in creating a concrete model, from which to establish a relationship with the respective controller.

This model will be based on a web page generator class, and its signature is shown below. Please take a look:

// define ‘WebPage’ class (model)
class WebPage{
    private $pageController;
    private $controllerStyle;
    private $page=”;
    public function __construct(PageController $pageController){
        $this->pageController=$pageController;
        $this->controllerStyle=$pageController->getStyle();
    }
    public function doHeader(){
        $this->page=’<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Strict//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd”><html xmlns=”http://www.w3.org/1999/xhtml” xml:lang=”es” lang=”es”><head><meta http-equiv=”Content-Type” content=”text/html; charset=UTF-8″ /><link rel=”stylesheet” href=”defaultstyle.css” type=”text/css” /><title>Sample Web Page</title></head>’;
    }
    public function doBody(){
        $this->page.=’<body><div id=”header”><h1>Header section</h1></div><div id=”navbar”><ul><li><a href=”#” title=”Link 1″>Link 1</a></li><li><a href=”#” title=”Link 2″>Link 2</a></li><li><a href=”#” title=”Link 3″>Link 3</a></li><li><a href=”#” title=”Link 4″>Link 4</a></li><li><a href=”#” title=”Link 5″>Link 5</a></li><li><a href=”#” title=”Link 6″>Link 6</a></li></ul></div><div id=”leftcol”><h1>Left column</h1></div><div id=”centercol”><h1>Center column</h1></div><div id=”rightcol”><h1>Right column</h1></div>’;
    }
    public function doFooter(){
        $this->page.=’<div id=”footer”><h1>Footer section</h1></div></body></html>’;
    }
    public function getPage(){
        return $this->page;
    }
    public function getControllerStyle(){
        return $this->controllerStyle;
    }
}
 

If you examine the above class’ source code, then you’ll quickly understand its functionality, since its structure is quite simple. In short, this web page generator class presents some straightforward methods which are responsible for building the three typical sections that comprise a web document.

Of course, here I’m speaking of a heading section, a main container and finally a footer area, which are generated by the respective “doHeader(),” “doBody()” and “doFooter()” methods. Also, you should notice how this class takes up an object of type “PageController,” which is directly assigned as a new class property.

However, and leaving out for a moment the methods that I just described, you should pay attention to the relationship established between the controller class that you learned before and this one. Notice how the controller class indicates to the model (in this case, the web page generator) what style sheet should be utilized when the web document is rendered, by using the “getControllerStyle()” method.

Now, are you starting to see how simple it is to define a proper interaction between the controller and the model? I hope you are!

Well, having defined the first two primary elements of this basic web page controller schema, obviously I need to create the third component that completes this scenario. As you might have guessed, I’m talking about a new PHP class, which will use the web document’s source code to attach to it different style sheets on the fly.

Within the MVC schema, this new class should be called the “View” component, and it’s the subject of the next section. Thus, click on the link below and learn how this class will be constructed.

{mospagebreak title=Completing the MVC schema: defining a style sheet generator class}

As I explained in the previous section, the “View” element included within the MVC schema will be represented by a style sheet generator class. This class will be tasked with rendering the previous web page in accordance with the type of style indicated originally by the corresponding web page controller.

Based on the above concepts, this new class is defined as follows:

// define ‘StyleGenerator’ class (view)
class StyleGenerator{
    private $webPage;
    public function __construct(WebPage $webPage){
        $this->webPage=$webPage;
    }
    public function generateStyle(){
        return str_replace(‘defaultstyle’,$this->webPage-
>getControllerStyle(),$this->webPage->getPage());
    }
}

As you can see, the “StyleGenerator” class listed above also accepts the respective “WebPage” object (remember again that this is the model), and uses the “generateStyle()” method to attach a style sheet to the whole web page. Again, you should notice how the pertinent style is tied to the web document, based on the “decisions” made by the controller class.

At this stage, I feel pretty satisfied, because I’ve defined the three elements that comprise the complete MVC schema. Therefore, it’s time to put all the classes together and see how different style sheets (called “views”) can be dynamically attached to the web document created by the previous “WebPage” class.

To see how this will be done, you’ll have to read the upcoming section, thus click on the following link.

{mospagebreak title=Putting the MVC schema to work: generating style sheets on the fly}

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:

“styles1.css” file

body{
    margin: 0;
    padding: 0;
    background: #fff;
}
h1 {
    font: bold 22px Arial, Tahoma;
    color: #000;
    margin: 0;
}
#header{
    height: 100px;
    background: #9c0;
}
#navbar{
    background: #cfc;
    padding: 4px 0 4px 20%;
}
#navbar ul{                  
    display: inline;
}
#navbar li{
    list-style-type: none;    
    display: inline;
}
#navbar a, #navbar a:visited{ 
    display: block;
    float: left;
    width: 100px;
    height: 15px;
    padding: 2px 0 0 0;
    margin-right: 4px;
    font: normal 11px Tahoma, Arial;
    color: #000;
    text-align: center;
    text-decoration: none;
    border: 1px solid #000;
}
#navbar a:hover{
    background: #fff;
}
#leftcol{
    float: left;
    width: 20%;
    height: 500px;
    background: #9c0;
}
#centercol{
    float: left;
    width: 58%;
    height: 500px;
    background: #fff;
}
#rightcol{
    float: right;
    width: 20%;
    height: 500px;
    background: #9c0;
}
#footer{
    clear: left;
    height: 20px;
    background: #cfc;
}

“styles2.css” file

body{
    margin: 0;
    padding: 0;
    background: #fff;
}
h1 {
    font: bold 22px Arial, Tahoma;
    color: #000;
    margin: 0;
}
#header{
    height: 100px;
    background: #f60;
}
#navbar{
    background: #cfc;
    padding: 4px 0 4px 20%;
}
#navbar ul{
    display: inline;
}
#navbar li{
    list-style-type: none;
    display: inline;
}
#navbar a, #navbar a:visited{
    display: block;
    float: left;
    width: 100px;
    height: 15px;
    padding: 2px 0 0 0;
    margin-right: 4px;
    font: normal 11px Tahoma, Arial;
    color: #000;
    text-align: center;
    text-decoration: none;
    border: 1px solid #000;
}
#navbar a:hover{
    background: #fff;
}
#leftcol{
    float: left;
    width: 20%;
    height: 500px;
    background: #f60;
}
#centercol{
    float: left;
    width: 58%;
    height: 500px;
    background: #fff;
}
#rightcol{
    float: right;
    width: 20%;
    height: 500px;
    background: #f60;
}
#footer{
    clear: left;
    height: 20px;
    background: #cfc;
}

“styles3.css” file

body{
    margin: 0;
    padding: 0;
    background: #fff;
}
h1 {
    font: bold 22px Arial, Tahoma;
    color: #000;
    margin: 0;
}
#header{
    height: 100px;
    background: #9cf;
}
#navbar{
    background: #cfc;
    padding: 4px 0 4px 20%;
}
#navbar ul{
    display: inline;
}
#navbar li{
    list-style-type: none;
    display: inline;
}
#navbar a, #navbar a:visited{
    display: block;
    float: left;
    width: 100px;
    height: 15px;
    padding: 2px 0 0 0;
    margin-right: 4px;
    font: normal 11px Tahoma, Arial;
    color: #000;
    text-align: center;
    text-decoration: none;
    border: 1px solid #000;
}
#navbar a:hover{
    background: #fff;
}
#leftcol{
    float: left;
    width: 20%;
    height: 500px;
    background: #9cf;
}
#centercol{
    float: left;
    width: 58%;
    height: 500px;
    background: #fff;
}
#rightcol{
    float: right;
    width: 20%;
    height: 500px;
    background: #9cf;
}
#footer{
    clear: left;
    height: 20px;
    background: #cfc;
}

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();
}

// display web page with the third style sheet

try{
    $pageController=new PageController(‘styles3′);
    $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! 

[gp-comments width="770" linklove="off" ]
antalya escort bayan antalya escort bayan