Personally I use the Smarty template engine for all HTML output (and email too). Each page runs in its own .php file which has a structure similar to this:
require('includes/common.php'); // Pulls all our common stuff in
function ShowForm() // For example, not every page has a function called showform, some have more than one
{
$smarty = new Smarty_Custom();
// Here I would assign some fields into smarty
$smarty->display('sometemplate.tpl');
}
function DoSave()
{
// Do some processing of a form for example.
}
// Here I would do any POST processing etc...
if (WasButtonPressed('save')) {
DoSave();
}
ShowForm();
The basic aims are:
- Minimum repeated code
- Everything is in a function - this is required because PHP doesn't have lexical scope therefore the only way of scoping a variable (other than manually calling unset) is to put all code in functions.
My common.php sets up the include paths and then includes further files as necessary. I always use require() rather than include to include things- as this causes a fatal if it fails, preventing the script from running further (which is good, as this could cause further errors).
Most of my includes only define functions and constants (plus a few classes). There are a few minor exceptions to this rule, such as if I'm using sessions or setting up specific headers, but I find it easier to not having things done "automatically" by common.php as it makes it difficult to reverse some of those things later.
Mark