Building Object-Oriented Web Pages with Inheritance in PHP 5

You have probably used the principles of inheritance in any number of your object-oriented programming projects. Traditionally this means working with parent and child classes during the creation of a PHP application. In this two-part series, you’ll learn a simple way to use inheritance while creating object-oriented web pages.

Introduction

As the clever PHP developer that you surely are, it’s quite probable that you’ve already used the object-oriented paradigm to develop one or more web applications. This implies that defining a few classes along with their methods and properties should be a pretty familiar procedure to you. Definitely, it must be admitted that building object-based applications with a friendly scripting language like PHP is not only a truly educational experience, since it requires at least a basic knowledge of software engineering, but fun as well. 

As you possibly know, after a decent time working with this approachable — yet mature — web development language, it’s possible to create scripts that implement a certain level of complexity, particularly when it comes to defining different relationships between several objects. And now that I mentioned the term "relationship," I’m pretty sure that you’ll be familiar with the two main pillars of this huge area of object-oriented programming. I mean aggregation and composition.

However, while learning to aggregate and compose classes with PHP (or any other programming language, naturally) can be a significant step toward mastering the fundamentals of software development, it’s fair to say that these two proven models of object interaction would be rather pointless if inheritance is deliberately left out of the learning process.

Perhaps, at the moment of reading the previous sentence you feel inclined to congratulate yourself, since you have already worked with parent and child classes here and there during the creation of a given PHP application. But one question is in order here: can inheritance be used in some way that is simpler than the traditional one, even with the purpose of doing something as trivial as building dynamic, object-oriented web pages?

To your satisfaction (and mine, of course) the answer to the above question is a resounding yes! Actually, by using the basic principles of inheritance, it’s feasible to create entire, consistent-looking web sites, with only a little effort and an intermediate background in object-oriented programming.

So, now that I have introduced this instructive subject, in the two articles in this series I’m going to show you how to build a sample object-based web site from its bare bones structure, by using the encapsulated logic of some parent and child PHP 5 classes. In this way I’ll demonstrate how inheritance can be used to tackle a concrete project, such as constructing dynamic web pages.

All right, it’s time to move forward and start learning how to utilize a simple classes hierarchy to create an expandable web site. Let’s begin now!

{mospagebreak title=Establishing a basic class hierarchy}

Since the main goal of this series is to illustrate how inheritance can be used to build an object-oriented web site, I’m going to define a base web page class, which will be tasked with setting up the blueprints for all the child objects derived from it.

This being said, the corresponding signature for this brand new web page class is listed below:

// define abstract ‘WebPage’ class
abstract class WebPage{
   private $html;
   private $title;
   private $mainLinks;
   private $content;
   abstract public function __construct($title,$content);
   abstract public function buildMetaData();
   abstract public function buildStyles();
   abstract public function buildHeader();
   abstract public function buildLinks();
   abstract public function buildBody();
   abstract public function buildFooter();
}

As shown above, the "WebPage" class has been defined as abstract, since it only establishes a generic model of how to build a simple web page. This is clearly reflected by the abstract methods declared by the class in question.

Besides, it’s worthwhile to mention here that the previous base class presents a very straightforward structure for outlining the generic characteristics of a basic web document. Nonetheless, as you’ll see in a few moments, all the child classes created from this parent will implement concretely all of its methods, in this way allowing the creation of a specific web page.

So far, so good right? At this point you learned how to build a base web page class, which simply behaves as an interface for generating specific web documents. Thus, considering the fact that you may want to see how a subclass derived from the previous parent "WebPage" can be provided with the required business logic to create a concrete web document, in the section to come I’m going to explain this procedure in detail.

So, want to learn how this brand new child class will be defined? Okay, click on the link below and keep reading.

{mospagebreak title=Using inheritance to derive a web page generator class}

As you’ll possibly recall from the previous section, I said that I was going to derive a child class from the prior parent "WebPage" to implement all of its abstract methods, and in consequence, define a class capable of displaying a basic web document.

Based on this premise, below I included the signature of a brand new class, called "HomeWebPage." As its name suggests, it is responsible for creating the front page of a fictional web site. The definition for this class is as follows:

// define concrete ‘HomeWebPage’ class
class HomeWebPage extends WebPage{
   // define default values for page links
   private $mainLinks=array(‘Home’=>’index.php’,’About
us’=>’about.php’,’Products’=>’products.php’,’Contact’=>
‘contact.php’);
   public function __construct($title=’Home Page’,$content=’This
is the default context for HOME web page’){        
     if(!$title||is_numeric($title)||strlen($title)>256){
       throw new Exception(‘Invalid title for the web page.’);
     }
     if(!$content){
       throw new Exception(‘Invalid contents for the web page.’);
     }
     $this->title=$title;
     $this->content=$content;           
   }
   // implement ‘buildMetaData()’ method
   public function buildMetaData(){
$output=<<<EOD

<!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">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-
8859-1" />

EOD;
     return $output;
   }
   // implement ‘buildStyles()’ method
   public function buildStyles(){
$output=<<<EOD
<style type="text/css">
body{
   padding: 0;
   margin: 0;
   background: #fff;
}

h2{
   margin: 0;
   font: bold 18px Arial, Helvetica, sans-serif;
   color: #000;      
}

p{
   font: normal 12px Arial, Helvetica, sans-serif;
   color: #000;      
}

#header{
   padding: 2%;
   background: #ffc;
}

#navbar{
   padding: 1% 2% 1% 2%;
   background: #fc0;
}

#navbar ul{
   list-style: none;
}

#navbar li{
   display: inline;
   padding-right: 4%;
}

#navbar a:link,#navbar a:visited{
   font: normal 12px Arial, Helvetica, sans-serif;
   color: #039;
   text-decoration: none;
}

#navbar a:hover{
   text-decoration: underline;
}

#mainwrapper{
   clear: both;
   height: 100%;
   overflow: hidden;
   background: #eee;
}

#mainwrapper .leftcol{
   position: relative;
   float: left;
}

#mainwrapper .rightcol{
   position: relative;
   float: right;
}

#leftbar{
   width: 16%;
   padding: 2%;
}

#centerbar{
   float: left;
   width: 55%;
   padding: 2%;
   background: #fff;
}          

#rightbar{
   width: 16%;
   padding: 2%;
}

#footer{
   clear: both;
   padding: 2%;
   background: #ffc;
}
</style>

EOD;
     return $output;
   }
   // implement ‘buildHeader()’ method
   public function buildHeader(){
$output.=<<<EOD

<title>$this->title</title>
</head>
<body>
<div id="header">
<h2>This is the header section of the web page</h2>
<p>Contents for header section go here.</p>
</div>

EOD;
     return $output;
   }
   // implement ‘buildLinks()’ method
   public function buildLinks(){
     $output='<div id="navbar">’."n".'<h2>This is the navigation
bar of the web page</h2>’."n".'<ul>’."n";
     foreach($this->mainLinks as $label=>$link){
       $output.='<li><a
href="’.$link.’">’.$label.'</a></li>’."n";
     }
     $output.='</ul>’."n".'</div>';
     return $output;
   }
   // implement ‘buildBody()’ method
   public function buildBody(){
$output=<<<EOD

<div id="mainwrapper">
  <div id="leftbar" class="leftcol">
    <h2>This is the left column of the web page</h2>
    <p>Contents for left column go here..</p>
  </div>
  <div id="centerbar" class="leftcol">
    <h2>This is the center column of the web page</h2>
    <p>$this->content</p>
  </div>
  <div id="rightbar" class="rightcol">
    <h2>This is the right column of the web page</h2>
    <p>Contents for right column go here.</p>
  </div>
</div>

EOD;
     return $output;
   }
   // implement ‘buildHeader()’ method
   public function buildFooter(){
$output.=<<<EOD

<div id="footer">
<h2>This is the footer section of the web page</h2>
<p>Contents for footer section go here.</p>
</div>
</body>
</html>

EOD;
     return $output;
   }
}

As you can see, the above "HomeWebPage" class is merely a child of the corresponding parent defined in the previous section, and implements all of its prior abstract methods to build the home page of a sample web site.

Of course, in this case the aforementioned "HomeWebPage" class uses a part of its logic to display the different sections of a basic web page, which implies that it deals at a certain level with the visual presentation of the web site in question. But, as you know, this isn’t a good practice in general terms, so this issue could be fixed easily by using a template instead of including hard-coded structural markup within some class methods.

However, in this case I’m going to keep the definition of the previous "HomeWebPage" class untouched, so you can see more clearly how an inherited class can be used to build a simple web page.

All right, having clarified this important point, it’s time to recapitulate what I have done so far. At this point I derived a child class from the corresponding parent, which comes in handy for displaying the home web page of a fictional site, a process that uses the principle of inheritance.

Nevertheless, I’d like to go one step further and show you how to utilize the same concept, but this time to create another web document of the sample web site in question. Maybe you think that this could be quickly achieved by deriving another subclass from the respective parent, and you’d be right.

But, in this case there’s a much better approach to follow. Since the initial "HomeWebPage" class already encapsulates all the logic required to display a web page, it’d be much easier to derive a child from it, and eventually override/overload some of its methods. Now, are you starting to realize how inheritance can be used in a simple fashion to build a complete web site? I bet you are!

So, now that I have generally outlined how a different web page of this fictional web site can be quickly built by using the functionality provided by inheritance, please jump into the next section and keep reading to learn how this process will be performed.

{mospagebreak title=Building another web page for a fictional web site}

As I stated in the previous section, building a different web page for this sample web site is only a matter of deriving another child class from the "HomeWebPage" (not from the base class), since it has already implemented the business logic required to display a complete web document.

So, bearing in mind this concept, below I included the definition of a brand new subclass, which displays the "About Us" section of this fictional web site.

Having said that, here’s the signature of this child class:

class AboutUsWebPage extends HomeWebPage{
   private $mainLinks=array(‘Home’=>’index.php’,’About
us’=>’about.php’,’Products’=>’products.php’,’Contact’=>
‘contact.php’);
   private $subLinks=array(‘Our company profile’=>’company.php’,’What customers are saying’=>’customers.php’);
   // implement ‘buildLinks()’ method
   public function buildLinks(){
     $output='<div id="navbar">’."n".'<h2>This is the navigation
bar of the web page</h2>’."n".'<ul>’."n";
     foreach($this->mainLinks as $label=>$link){
       $output.='<li><a href="’.$link.’">’.$label.'</a></li>’."n";
     }
     $output.='</ul><ul>';
     foreach($this->subLinks as $label=>$link){
       $output.='<li><a href="’.$link.’">’.$label.'</a></li>’."n";
     }
     $output.='</ul>’."n".'</div>';
     return $output;
   }
}

As you can see, the above "AboutUsWebPage" class only overrides the initial "buildLinks()" method implemented by its corresponding parent, with the purpose of displaying a few additional secondary links on the browser. However, as you might have guessed, the main advantage of this approach rests with using inheritance to create quickly the different sections of this sample web site. Quite simple, right?

Logically, if you’re anything like me, you might want to see the signature of the source files that display the respective "Home" and "About Us" sections of this sample web site. Below I listed the definitions of these files, in this way demonstrating how a few inherited classes can be used to build a complete object-oriented web site.

Given that, here are the source files in question:

(definition for index.php file)

<?php

try{
   // include parent classes
  
require_once ‘abstract_webpage.php';
  
require_once ‘homewebpage.php';

   // instantiate ‘HomeWebPage’ class
   $homePage=new HomeWebPage();
   // display web page
   echo $homePage->buildMetaData();
   echo $homePage->buildStyles();
   echo $homePage->buildHeader();
   echo $homePage->buildLinks();
   echo $homePage->buildBody();
   echo $homePage->buildFooter();
}
catch(Exception $e){
   echo $e->getMessage();
   exit();
}

(definition for about.php file)

try{
   // include parent classes 
   
require_once ‘abstract_webpage.php';
  
require_once ‘homewebpage.php';
  
require_once ‘aboutwebpage.php';

   // instantiate ‘AboutUsWebPage’ class
   $aboutPage=new AboutUsWebPage(‘About us’,’This is the default
content for ABOUT US page’);
   // display web page
   echo $aboutPage->buildMetaData();
   echo $aboutPage->buildStyles();
   echo $aboutPage->buildHeader();
   echo $aboutPage->buildLinks();
   echo $aboutPage->buildBody();
   echo $aboutPage->buildFooter();
}
catch(Exception $e){
   echo $e->getMessage();
   exit();
}

As you can see, building the different sections of this sample web site is a process reduced to including the required parent classes and instantiating the concrete class that displays a particular web page. Of course, in this case the functionality provided by inheritance is actually what makes creating distinct web documents a no-brainer process.

Finally, I suggest that you try creating your own web page generator classes, so you can understand more easily the way that inheritance can assist you in building dynamic web pages.

Final thoughts

In this first installment of the series, I hopefully illustrated how inheritance can be utilized in a helpful fashion to build the different web pages of a sample web site, whose look and feel is nearly the same across its respective sections.

However, this instructive journey hasn’t ended yet. In the last part I’m going to show you how to create some additional web pages to complete the structure of this fictional web site.

Now that I’ve told you about the topics that will be covered in the final article, I’m sure you won’t want to miss it!

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