Instead of using includes directly you should consider a simple template engine:
template.cls.php
Code: Select all
class Template{
function execute($file)
{
ob_start();
include_once($file);
$buff = ob_get_contents();
ob_end_clean();
return $buff;
}
}
That is literally all the code you need to develop complex, templatized HTML pages.
A template would look something like:
layout.tpl.php
Code: Select all
<html>
<head>
<title><?php echo $this->title; ?></title>
</head>
<body>
<?php echo $this->body; ?>
</body>
</html>
You initialize the template engine and use the template like so:
index.phpCode: Select all
$eng = new Template();
$eng->title = 'This is the title';
$eng->body = 'This is the body';
echo $eng->execute('layout.tpl.php');
The above template engine relies on PHP and it's expando property support. Assigning the 'title' and 'body' members and their values at runtime instead of declaring the member statically inside the class. Really you could use either technique.
Now inside index.php you can dynamically include data from HTML files or database tables, CSV, etc, etc...
index.php?page=2
Code: Select all
$eng = new Template();
$page = (int)$_GET['page'];
// Assume connection to database somewhere in bootstrap code
$sql = sprintf('SELECT * FROM pages WHERE id = %d', $page);
$res = mysql_query($sql);
$arr = mysql_fetch_array($res)
$eng->title = strip_tags($arr['title']);
$eng->body = $arr['body']; // Run this HTML through HTML purifier
echo $eng->execute('layout.tpl.php');
The number of dynamic sections of your web site is now only limited by your PHP template (layout.tpl.php) which is a reflection of your database schema. If you have several pages which reqauire different layouts, you can adjust those layouts using conditionals or just create separate layouts and use them conditionally.
If you are concerned about taxing your server, this approach is quite streamlined and doesn't actually burn a lot of cycles as the template engine is so simple it has hardly any over head, unlike Smarty.
Caching is an breeze to implement as well. Simply take the results before echo-ing to screen and save them to a static HTML in a cache directory. Of course you need to add the logic into index.php to check for cached pages and use them instead of generating a page on the fly, but thats trivial as well, assuming you have static pages, at least in nature.
The coolest part of this technique (output buffering) is you can perform all sorts of filtering on the results before display. For example, you can check referrer and if it's Google, Yahoo, etc. You can hilite keywords in your HTML pages. There are countless other things you can do as well.
Cheers
