FuelMedlem sedan okt. 20001 285 inlägg Kan detta göras annorlunda/bättre?
class template_page
{
function template_page($template)
{
$mmm = "D:/wamp/www/test/x/themes/default/" . $template . ".html";
if (file_exists($mmm))
{
$this->template_page = join("", file($mmm));
}
else
{
die("Template file $template not found.");
}
}
function parse_template($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_template($data) : $data;
$this->template_page = eregi_replace("%" . $tag . "%", $data,
$this->template_page);
}
}
else
{
die("No tags can be replaced.");
}
}
function output()
{
echo $this->template_page;
}
}
jmeMedlem sedan maj 20012 237 inlägg Iaf en sak: hårdkoda inte sökvägarna.
Sedan skulle jag hellre returnera datan i funktionen output() än att skriva ut den.
Jag skulle försöka använda preg_*-baserade regex-funktioner då de skall vara snabbare än ereg_*-baserade.
Om du kör med PHP5 så skulle jag använda exceptions istället för die().
FuelMedlem sedan okt. 20001 285 inlägg sökvägen var bara så när jag testade
class template_page
{
function template_page($template)
{
$mmm = BASE_ROOT . "/" . TEMPLATEPATH . "/" . $template . ".html";
if (file_exists($mmm))
{
$this->template_page = join("", file($mmm));
}
else
{
throw new Exception("Template file $template not found..");
}
}
function parse_template($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_template($data) : $data;
$this->template_page = eregi_replace("%" . $tag . "%", $data,
$this->template_page);
}
}
else
{
throw new Exception("No tags can be replaced.");
}
}
function output()
{
return $this->template_page;
}
}
och..
require('./load.php');
try
{
$page = new template_page("test");
$page->replace_tags(array(
"title" => "TESTING",
"description" => "Welcome to my test",
));
print $page->output();
}
catch (Exception $e)
{
echo "MSG: ", $e->getMessage(), "\n";
}
Värt att notera är att jag under mina 7år som hobby-php-kodare aldrig har använt classer förrän nu (senaste månaderna), därför kan det se lite förvirrat ut :l