05.05.2013 Views

Programming PHP

Programming PHP

Programming PHP

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Example 13-3. Template script (continued)<br />

if (!empty($name)) {<br />

// do something with the supplied values<br />

$template = "thankyou.template";<br />

$bindings['NAME'] = $name;<br />

}<br />

else {<br />

$template = "user.template";<br />

}<br />

echo FillTemplate($template, $bindings);<br />

Example 13-4 shows the FillTemplate( ) function used by the script in Example 13-3.<br />

The function takes a template filename (to be located in the document root in a directory<br />

called templates), an array of values, and an optional instruction denoting what<br />

to do if a marker is found for which no value is given. The possible values are:<br />

"delete", which deletes the marker; "comment", which replaces the marker with a<br />

comment noting that the value is missing; or anything else, which just leaves the<br />

marker alone.<br />

Example 13-4. The FillTemplate( ) function<br />

function FillTemplate($inName, $inValues = array( ),<br />

$inUnhandled = "delete") {<br />

$theTemplateFile = $_SERVER['DOCUMENT_ROOT'] . '/templates/' . $inName;<br />

if ($theFile = fopen($theTemplateFile, 'r')) {<br />

$theTemplate = fread($theFile, filesize($theTemplateFile));<br />

fclose($theFile);<br />

}<br />

$theKeys = array_keys($inValues);<br />

foreach ($theKeys as $theKey) {<br />

// look for and replace the key everywhere it occurs in the template<br />

$theTemplate = str_replace("\{$theKey}", $inValues[$theKey],<br />

$theTemplate);<br />

}<br />

if ('delete' == $inUnhandled ) {<br />

// remove remaining keys<br />

$theTemplate = eregi_replace('{[^ }]*}', '', $theTemplate);<br />

} elseif ('comment' == $inUnhandled ) {<br />

// comment remaining keys<br />

$theTemplate = eregi_replace('{([^ }]*)}', '',<br />

$theTemplate);<br />

}<br />

return $theTemplate;<br />

}<br />

Clearly, this example of a templating system is somewhat contrived. But if you think<br />

of a large <strong>PHP</strong> application that displays hundreds of news articles, you can imagine<br />

how a templating system that used markers such as {HEADLINE}, {BYLINE}, and<br />

300 | Chapter 13: Application Techniques<br />

This is the Title of the Book, eMatter Edition<br />

Copyright © 2002 O’Reilly & Associates, Inc. All rights reserved.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!