Page Layouts With PHP Functions

How to organize your layout without using more then one include.
on 03/15/10 at 00:00:00.
by rgk author list print the content item create pdf file of the content item
in Guides
 10.0 - 2 votes -

How many people are used to this: you have a header include file, footer include file, menu include file, advertisement include file and so on... well why not combine a lot more?

I like to name my main include file, main.php. Its simple and gets to the point. This will be the only file you need to include. I also place it inside an include folder, only include files should go in this folder for organization.
  1. include_once 'include/main.php';


Now you can use your main.php for a universal file. This helps you set error reporting and the timezone. In your main.php you can set this.
  1. ini_set('display_errors', 'On');
  2. error_reporting(E_ALL | E_STRICT);
  3.  
  4. date_default_timezone_set('America/New_York');

Obviously you can set any timezone you want, and do what you like with error reporting.

Now lets define your URL.
  1. $url = 'http://your.url/';
  2. define('URL', $url);

We can use this to know exactly what your URL is. You can use more automatic ways to get your URL also.

Now creating the layout functions, its pretty simple. I show you a head() function first, which can be used to show header information.
  1. function head($page) {
  2.  
  3.         $style = URL . '/css/style.css';
  4.  
  5.         echo '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">' . "\n" .
  6.         '<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">' . "\n" .
  7.         '<head>' . "\n" .
  8.  
  9.         '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />' . "\n" .
  10.         '<title>Your Site : ' . $page . '</title>' . "\n" .
  11.         '<link rel="stylesheet" type="text/css" href="' . $style . '" />' . "\n" .
  12.  
  13.         '</head>' . "\n" .
  14.         '<body>' . "\n";
  15. }

As you can see the $page variable allows you to set what page your actually on.

A footer is just as simple.
  1. function foot() {
  2.         echo '<div id="footer">' . "\n" .
  3.         '<p><a href="' . URL . '">Home</a> - <a href="' . URL . 'about.php">About</a> - <a href=" ' . URL . 'contact.php">Contact</a></p>' . "\n" .
  4.         '</div>' . "\n" .
  5.         '</body>' . "\n" .
  6.         '</html>' . "\n";
  7. }


And now you can construct a page with just this.
  1. <?php
  2.         include_once 'include/main.php';
  3.         head('Home');
  4.         foot();
  5. ?>

Render time: 0.2268 sec, 0.0175 of that for queries. DB queries: 48. Memory Usage: 3,744kB