Sharing a common heading, footer and menu in PHP
The heading, footer and menu of this website appear consistently on every page.
99% of websites do this, and the PHP inside each probably looks a little like this:
<?php
$page_title="Star wars figures";
$meta_keywords="star,wars,figures,jedi";
require_once "header.php";
?>
Hans Solo, blah, blah<br />....
<?php
require_once "footer.php";
?>
For simple websites this is fine, but as your website grows and you need slightly customised headers and footers it can quickly become unmanageable.
Our class-based system
The system we have settled on appears below, and has these advantages:
- All 'customising variables' (heading and footer) go at the page top
- 'Customising variables' are in an array, so they're future proof, and don't litter the global namespace
- Footer gets rendered automatically
- Common HTML generating functions could be added to the class
- VAT rate, telephone, email address etc could be added to the class as const's
An example page ...
<?php
$temp['title'] = 'Star wars action figures';
$temp['javascripts'] = array('effects.js', 'validate.js');
$temp['js_onload'] = 'jsInit();';
$m3page = new m3page($temp); // class constructor will render the page top
?>
Hans Solo, blah, blah<br />....
<!-- script ends here, so class destructor will render page bottom -->
Page uses this class ...
<?php
class m3page
{
private $bespoke;
public function __construct($bespoke)
{
$this->bespoke=$bespoke;
echo "<html>\n";
echo "<head>\n";
echo "<title>{$bespoke['title']}</title>\n";
foreach($bespoke['javascripts'] AS $javascript)
echo "<script language='javascript' src='$javascript'></script>\n";
echo "</head>\n";
if ($bespoke['js_onload']=='') echo "<body>\n";
else echo "<body onload='{$bespoke['js_onload']}'>\n";
echo "<div id='heading'>\n";
echo "<img src='logo.png' />\n";
echo "</div>\n";
echo "<div id='menu'>\n";
echo "<a href='index.php'>Home</a>\n";
echo "<a href='about.php'>About Us</a>\n";
echo "<a href='faq.php'>FAQ</a>\n";
echo "</div>\n";
echo "<div id='content'>\n";
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
function __destruct()
{
echo "\n";
echo "</div>\n"; // #content
echo "</body>\n";
echo "</html>\n";
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
}
?>
Page generates this HTML ...
<html>
<head>
<title>Star wars action figures</title>
<script language='javascript' src='effects.js'></script>
<script language='javascript' src='validate.js'></script>
</head>
<body onload='jsInit();'>
<div id='heading'>
<img src='logo.png' />
</div>
<div id='menu'>
<a href='index.php'>Home</a>
<a href='about.php'>About Us</a>
<a href='faq.php'>FAQ</a>
</div>
<div id='content'>
Hans Solo, blah, blah<br />....
<!-- script ends here, so class destructor will render page bottom -->
</div>
</body>
</html>