Writing Your Own Template Caching Class In PHP - Real-World Examples (Page 5 of 6 ) A Simple Iteration Here's an example on how you can iterate through an array. We'll fetch some rows from a table and place them in an array that the template can iterate through. Note: In all of the examples I've placed the class under a directory called 'include' and the templates under a directory called 'templates'. The cache gets saved to a directory called 'cache'. First of all, we'll make a database table and add some values to it. Here's the SQL statements: CREATE TABLE books ( id mediumint(9) NOT NULL auto_increment, title varchar(255) NOT NULL, author varchar(255) NOT NULL, PRIMARY KEY (id) ) TYPE=MyISAM;
INSERT INTO books (id, title, author) VALUES("21", "Applied Microsoft .NET Framework Programming", "Jeffrey Richter");
INSERT INTO books (id, title, author) VALUES("22", "Adobe Photoshop 7.0 Classroom in a Book", "Adobe Creative Team");
INSERT INTO books (id, title, author) VALUES("23", "Cisco CCNA Exam #640-607 Certificatoin Guide (3rd Edition)", "Wendell Odom");
INSERT INTO books (id, title, author) VALUES("24", "A+ Certification All-in-One Exam Guide", "Michael Meyers");
INSERT INTO books (id, title, author) VALUES("25", "Photoshop 7 Down & Dirty Tricks", "Scott Kelby");
INSERT INTO books (id, title, author) VALUES("26", "Newton\'s Telecom Dictionary: The Authoritative Resource for Telecommunications, Networking, the Internet and Information Technology (18th Edition)", "Harry Newton, Ray Horak");
INSERT INTO books (id, title, author) VALUES("27", "Adobe Illustrator 10 Classroom in a Book", "Adobe Creative Team");
INSERT INTO books (id, title, author) VALUES("28", "Professional ASP.NET 1.0 (2002 Edition)", "Alex Homer, Dave Sussman");
INSERT INTO books (id, title, author) VALUES("29", "Macromedia Flash MX ActionScripting: Advanced Training from the Source", "Derek Franklin, Jobe Makar"); Now we can go on to the PHP part: <?php
// Include the template class require_once('include/Template.php');
// Instantiate the template class $tpl = new Template();
// Set database connection variables $dbhost = 'localhost'; $dbpass = 'password'; $dbuser = 'username'; $dbname = 'library';
// Connect to mysql and select the db mysql_connect($dbhost, $dbuser, $dbpass); mysql_select_db($dbname);
// Query the database $result = mysql_query('SELECT id, title, author FROM books');
// Put the result in an array while ($row = mysql_fetch_array($result)) { $booklist[] = array( 'id' => $row['id'], 'title' => $row['title'], 'author' => $row['author'] ); }
// Add the variable $tpl->addVar('booklist', $booklist);
// Display the template $tpl->display('templates/iteration.tpl.html');
?> Here's an example on how the array is structured after processing: Array ( [0] => Array ( [id] => 21 [title] => Applied Microsoft .NET Framework Programming [author] => Jeffrey Richter )
[1] => Array ( [id] => 22 [title] => Adobe Photoshop 7.0 Classroom in a Book [author] => Adobe Creative Team ) ) The template code needed to iterate through the array is quite simple: <html> <head> <title>Simple Iteration</title> </head>
<body>
<table border="0" cellpadding="3">
<tr bgcolor="#CFCFCF"> <td><strong>Id</strong></td> <td><strong>Title</strong></td> <td><strong>Author</strong></td> </tr>
<? foreach ($booklist as $book) { ?> <tr bgcolor="#F2F2F2"> <td><?=$book['id']?></td> <td><?=$book['title']?></td> <td><?=$book['author']?></td> </tr> <? } ?>
</table>
</body> </html> As you can see, all we do is use a "foreach" construct to iterate through the array. If you prefer something else, you may use that too. That's the beauty of having PHP as the template language. Let's go on to an example on caching. Caching in Action If you're wondering how you're supposed to use the caching feature in your pages, then I'll explain it to you here. I will still be using the same database table as in the last example: <?php
// Include the template class require_once('include/Template.php');
// Instantiate the template class $tpl = new Template();
// Set the cache properties $tpl->setCacheDir('cache'); $tpl->setCacheLifetime(10); $tpl->setCaching(true);
// Prepare the input $id = isset($_GET['id']) ? addslashes($_GET['id']) : false;
if (!$tpl->isCached('caching.tpl.html', $id)) { // Set database connection variables $dbhost = 'localhost'; $dbpass = 'password'; $dbuser = 'username'; $dbname = 'library';
// Connect to mysql and select the db mysql_connect($dbhost, $dbuser, $dbpass); mysql_select_db($dbname);
// Query the database $result = mysql_query("SELECT id, title, author FROM books WHERE id = '$id'");
if (mysql_num_rows($result)) { // Add the variables $tpl->addVar('id', mysql_result($result, 0, 'id')); $tpl->addVar('title', mysql_result($result, 0, 'title')); $tpl->addVar('author', mysql_result($result, 0, 'author')); }
echo "<h1>This page wasn't fetched from the cache</h1>"; } else { echo "<h1>This page was fetched from the cache</h1>"; }
// Display the template $tpl->display('templates/caching.tpl.html', $id);
?> This page fetches the information about one of the entries in the books table. By using caching, we can tell PHP only to connect to the database and fetch the info when the page isn't cached. This is an example on how the filename and caching id’s work together. By supplying a cache id, we make sure that the pages are cached separately. Let's take a closer look at some parts of the code: // Set the cache properties $tpl->setCacheDir('cache'); $tpl->setCacheLifetime(10); $tpl->setCaching(true); This part does just what the comment says. It turns caching on, and changes some of the cache properties. You can see that we set the cache directory to be 'cache'. Make that directory before executing this page. We also set the cache lifetime to 10 seconds, because this is an example and we want to see that the lifetime does indeed work. if (!$tpl->isCached('caching.tpl.html', $id)) { This if construct checks if the page and id is cached already. If it is cached, it will skip the database part and just continue. [Note] It's important that you supply an $id to the display() method too! [End Note] To view a specific ID, just add (for example) id=5 at the end of the URL (ie. caching.php?id=5). Let's go on to the template code. <html> <head> <title>Caching in Action</title> </head>
<body>
<table border="0" cellpadding="3">
<tr bgcolor="#CFCFCF"> <td><strong>Id</strong></td> <td><strong>Title</strong></td> <td><strong>Author</strong></td> </tr>
<? if ($id && $title && $author) { ?>
<tr bgcolor="#F2F2F2"> <td><?=$id?></td> <td><?=$title?></td> <td><?=$author?></td> </tr>
<? } else { ?>
<tr bgcolor="#F2F2F2"> <td colspan="3">Couldn't find the specified book-id.</td> </tr>
<? } ?>
</table>
</body> </html> You've now created a page that connects to the database only when it doesn't find the page in the cache. If caching is used on heavy load servers then the server load can be reduced quite significantly. Alternating Colors You may have seen alternating colors in tables before. It's pretty easy to do. Using the PHP code for the first example (simple iteration), we can just replace the template with this template: <html> <head> <title>Simple Iteration</title> </head>
<body>
<table border="0" cellpadding="3">
<tr bgcolor="#CFCFCF"> <td><strong>Id</strong></td> <td><strong>Title</strong></td> <td><strong>Author</strong></td> </tr>
<? $i = 0 ?> <? foreach ($booklist as $book) { ?> <? $color = $i % 2 ? '#f5f5f5' : '#ffffff' ?>
<tr bgcolor="<?=$color?>"> <td><?=$book['id']?></td> <td><?=$book['title']?></td> <td><?=$book['author']?></td> </tr>
<? $i++ ?> <? } ?>
</table>
</body> </html> That's it! Pretty easy, right? I've run out of examples now, so let's continue on to the conclusion. Next: Conclusion >>
More MySQL Articles More By Havard Lindset |