Completing a Web Site Template using Inheritance in PHP 5

If you’re a PHP developer who develops object-oriented applications on a frequent basis, then you’ll know that inheritance can be an extremely useful concept that might help in reusing code when it comes to creating a hierarchy of classes. This article, and yesterday’s, take advantage of this powerful concept and show you how to use some straightforward classes to build a complete web site that presents a consistent look across its pages.

Introduction

Now that I have introduced the topics that will be covered in these tutorials, let me briefly recapitulate contents of the first part of the series, in case you didn’t read that article.

As I stated at the beginning, the remarkable functionality provided by inheritance can be used in all sorts of clever ways, including the development of database abstraction layers, form generating and validating systems, error loggers, and so forth. However, in this situation I decided to demonstrate how a well-defined set of hierarchical classes can be utilized with the purpose of creating the different sections that comprise a simple web site.

Even though the project itself may look rather primitive at first sight, it’s useful for illustrating yet another approach to building web sites that expose a consistent visual appearance across their pages. And speaking specifically of creating a web site by using the concept of inheritance, you’ll possibly remember that over the course of the preceding article, I showed you how to develop the classic "Home" and "About us" pages of a fictional web site utilizing a couple of inherited classes, whose respective signatures were indeed very easy to code.

Thus, taking into account the same development methodology I described above, in this final installment of the series I’m going to complete the creation of the sample website by developing a pair of additional web pages, which will come in useful for building the typical "Products" and "Contact" sections of the web site in question.

The experience will be instructive, so let’s discover the real power behind using inheritance with PHP 5. Let’s get started!

{mospagebreak title=Listing the signatures of the web site’s base classes}

Before I start demonstrating how to incorporate the "Products" and "Contacts" sections into the sample web site, I’d like to list once again the corresponding definitions of the base classes that behave like the real workhorses of this web site generating application.

Given that, here are the code samples for the original classes. Please examine them. 

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

Now that you hopefully recalled how the previous base classes worked, pay attention to the definition of the following PHP file, which was responsible for displaying the "home" page of this fictional web site:

(definition for index.php file)

<?php
try{
   // 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();
}
?>

After studying the signature of the previous PHP, definitely you’ll have to agree with me that building the different sections of a sample web site is actually a no-brainer process because of the functionality provided by inheritance.

So far, so good, right? Now that you have hopefully recalled how to use the  "HomeWebPage" class to create the corresponding web page, I believe that it’s a good time to move forward to see how the respective "Products" and "Contact" sections can be similarly generated by using most of the functionality of the base "HomeWebPage" class.

Want to see how these brand new sections of this sample web site will be built? Click on the link that appears below and keep reading.

{mospagebreak title=Extending the usage of inheritance}

As I mentioned in the previous section, I’m now going to create a classic "Products" web page by deriving a subclass from the "HomeWebPage" class that you saw earlier.

This being said, here is the definition for the brand new "Products" web page:

class ProductWebPage extends HomeWebPage{
   private $mainLinks=array(‘Home’=>’index.php’,'About
us’=>’about.php’,'Products’=>’products.php’,'Contact’=>
‘contact.php’);
   private $subLinks=array(‘PHP
Software’=>’phpsoftware.php’,'JavaScript
libraries’=>’jslibraries.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 shown above, the "ProductWebPage" class has been created as a child class of the initial "HomeWebPage," which demonstrates in a nutshell how inheritance can be used in a simple way to build the diverse sections of a given web site.

Now that you have seen the signature of the "ProductWebPage," please pay careful attention to the following script, which is tasked with displaying the "Products" web page in question:

try{
   // instantiate ‘ProductWebPage’ class
   $productPage=new ProductWebPage(‘Products’,'This is the default content for PRODUCTS page’);
   // display web page
   echo $productPage->buildMetaData();
   echo $productPage->buildStyles();
   echo $productPage->buildHeader();
   echo $productPage->buildLinks();
   echo $productPage->buildBody();
   echo $productPage->buildFooter();
}
catch(Exception $e){
   echo $e->getMessage();
   exit();
}

As you can see, building a specific web page for this fictional web site is reduced to deriving a subclass from the corresponding parent, and overriding/overloading one or more of its methods, according to the requirements of that particular section.

Finally, I’d like to show you the complete signature of the basic "Products" web page that was built earlier, this time including the respective parent classes:

(definition for products.php file)

<?php
try{
   // include parent classes
  
require_once ‘abstract_webpage.php’;
  
require_once ‘homewebpage.php’;
  
require_once ‘productswebpage.php’;

   // instantiate ‘ProductWebPage’ class
   $productPage=new ProductWebPage(‘Products’,'This is the
default content for PRODUCTS page’);
   // display web page
   echo $productPage->buildMetaData();
   echo $productPage->buildStyles();
   echo $productPage->buildHeader();
   echo $productPage->buildLinks();
   echo $productPage->buildBody();
   echo $productPage->buildFooter();
}
catch(Exception $e){
   echo $e->getMessage();
   exit();
}

?>

Okay, now that you have grasped the approach used in creating the "Products" web page, let’s leap forward and see how to build the "Contact" section of this sample web site, thus completing the development of its basic structure.

To see how this last web page will be built, please read the next few lines. Don’t worry, since I’ll be there, waiting for you.

{mospagebreak title=Completing the development of the sample web site}

In consonance with the concepts expressed in the section that you just read, the last thing that I’m going to show you in this article will consist of building a typical "Contact" web page for the sample web site that you learned before.

Basically, the process required to create the web page is based upon deriving a subclass from the respective "HomeWebPage" parent, as I did previously with the other web site sections; by this time, that concept that shouldn’t be hard to grasp for you at all.

Now that I have explained how this brand new class will be defined, please focus your attention on the following code sample, which shows its signature:

class ContactWebPage extends HomeWebPage{
   private $mainLinks=array(‘Home’=>’index.php’,'About
us’=>’about.php’,'Products’=>’products.php’,'Contact’=>
‘contact.php’);
   private $subLinks=array(‘Email
contact’=>’email.php’,'HeadQuarters’=>’headquarters.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;
   }
}

I won’t stop for long to explain how the above class works, since its logic is nearly identical to the examples shown in the previous sections. Instead, I’m going to list the complete definition of a hypothetical "Products" web page, including the required parent classes:

That being said, here’s how this PHP file looks:

<?php

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

   // instantiate ‘ContactWebPage’ class
   $contactPage=new ContactWebPage(‘Contact’,'This is the default
content for CONTACT page’);
   // display web page
   echo $contactPage->buildMetaData();
   echo $contactPage->buildStyles();
   echo $contactPage->buildHeader();
   echo $contactPage->buildLinks();
   echo $contactPage->buildBody();
   echo $contactPage->buildFooter();
}
catch(Exception $e){
   echo $e->getMessage();
   exit();
}

?>

As demonstrated above, that’s all the PHP code required to build a basic "Contact" web page, thanks to the capacity provided by inheritance. Please feel free to modify all the sample classes shown here, so you can develop your own examples for testing, and eventually acquire a better grounding in how to work with inherited classes in PHP 5.

Final thoughts

Sadly, this is the end of the series. As you have learned, inheritance is indeed a very powerful concept that allows, among other neat things, the development of object-oriented web sites. Of course, for larger applications the approach shown here isn’t very suitable, but for small ones, the implementation of this technique, along with a simple template system, might be a pretty efficient solution.

See you in the next PHP tutorial!

Google+ Comments

Google+ Comments