template and file read
| From: | EE | Date: | Tue, 20 Jul 2004 19:53:18 +0000 |
| Subject: | template and file read | ||
| Groups: | php.general | ||
| Request: | Send a blank email to php-general+get-191225@lists.php.net to get a copy of this message | ||
Dears,
In one of the tutorials I read about templates, the writer is diving the
code into multiple files. He put the menu, main, left, right, footer
each in a separate file. He is using foreach to go through an array and
reads all these files.
Is this a good practice?
Would this slow down the site?
---THE WRITER'S CODE---
<?php require_once('lib/template.php');
$page = new Page('std.tpl');
$page->replace_tags(array( 'title' => 'HOME',
'description' => 'Welcome to my website!',
'main' => 'dat/index.dat',
'menu' => 'dat/menu.dat',
'left' => 'dat/submenu.dat',
'right' => 'dat/right.dat',
'footer' => 'dat/footer.php'));
$page->output(); ?>
//template.php
<?php class Page {
var $page;
function Page($template = 'std.tpl') {
if (file_exists($template)) $this->page = join('', file($template));
else die("Template file $template not found.");
}
function parse($file) {
ob_start();
include($file);
$buffer = ob_get_contents(); ob_end_clean();
return $buffer;
}
function replace_tags($tags = array()) {
if (sizeof($tags) > 0)
foreach ($tags as $tag => $data) {
$data = (file_exists($data)) ? $this->parse($data) : $data;
$this->page = eregi_replace('{' . $tag . '}', $data, $this->page);
}
else die('No tags designated for replacement.');
}
function output() {
print($this->page);
}
}
?>