How to Easily Manage HTML Output in PHP

I thought I’d come out with the big guns for our inaugural post. If you’ve ever written a PHP-powered site, you’ll know that the mix of PHP and HTML in the same document can quickly become hideous to read and a nightmare to maintain.
The usual solution is o use a template engine like Smarty, but these are hard to learn and are overkill for smaller projects.
What’s a developer to do?
Enter phpSprockets, a library written at Innova Partners in Columbus OH. Take a normal PHP document that loops over database records and outputs a table:
<table> <tr> <th>Name</th> <th>Address</th> </tr> <?php // assume $rows has been fetched from the database $class = 'alt'; foreach ($rows as $row) { if ($class == '') { $class = 'alt'; } else { $class = ''; } ?> <tr class="<?php echo $alt ?>"> <td><?php echo ucwords($row['name']) ?></td> <td><?php echo $row['address'] ?> </td> </tr> <?php } echo "</table>"; ?>
That’s a lot of code for a simple task, and it’s already a mess. We’re applying a different class to alternating rows, we’re jumping into PHP from HTML, and if we need to do anything complex to this or add more rows this will quickly become unmaintainable. If you had to work with code like this, you’d hate your job eventually.
Let’s see the same code in phpSprockets:
<?php $table = new Sprocket('table'); $headers = $table->tr(); $headers->th('Name'); $headers->th('Address'); $class = 'alt'; foreach ($rows as $row) { if ($class == '') { $class = 'alt'; } else { $class = ''; } $tr = $table->tr(); if ($class != '') { $tr->class = $class; } $tr->td($row['name']); $tr->td($row['address']); } ?>
Okay, the phpSprockets code is longer, but you never leave PHP-mode, and everything’s very readable. I didn’t comment either chunk of code, but once you’ve learned the simple phpSprockets syntax you’ll find that it’s much easier to go back in five months and make changes, which isn’t something you can say about stock PHP without being very rigorous about coding style. Since starting with Innova Partners I’ve switched to using phpSprockets for every PHP project I work on, and the benefits are remarkable.
This is an intentionally brief introduction. For a more in-depth look watch the introductory screencast (by me!), and for full documentation and to download, visit our downloads page.
Share ThisTags: PHP, phpSprockets
January 24th, 2008 at 11:07 am
[...] « How to Easily Manage HTML Output in PHP Jan 24 2008 [...]
February 8th, 2008 at 1:23 am
[...] mentioned phpSprockets already — you did read the post and watch the screencast, right? — and that’s an [...]
June 5th, 2008 at 12:32 pm
If that’s what your regular PHP code looks like, then you’re doing something wrong. You should definitely try to separate layout & functionality - although I have to admit that this is not always possible. I do like the phpSprockets project though, and I’m sure I’ll use it in my next project. So thank you!