Simple Blog – Example 7: Smarty

Simple Blog is a multi-part series. Check out The Index

In the previous example, we improved our application’s models by rewriting the Database and Post classes using PHP Data Objects. In this example, we’ll shift focus to our application’s views. Until now, we’ve been using PHP’s own engine to render our view pages. Our view pages were made up of HTML interspersed with small block of PHP to import header and footer markup, iterate through arrays, and display the contents of variables. In this example, will integrate the Smarty Template Engine into our application which promises to truly separate presentation logic (HTML/CSS) from application logic (PHP).

In the process of researching this post, I hit up smarty.net to read up on the advantages of implementing their template engine. They claim that Smarty makes the development process easier, faster, and more maintainable. On the flip side, Smarty openly acknowledges that installing their template engine results in slower script execution as compared to native PHP. Obviously, introducing an additional layer of complexity to page rendering will result in slower execution; but how much slower? We’ll get to that …

So, let’s take a look at what Smarty has to offer. We’ll start by looking at our configuration file, where we’ve made a few administrative changes to get Smarty working. FYI, if you’re following along, take a look at Smarty’s quick install guide before proceeding.

Configuration File

Instead of listing the entire config file, I’d like to highlight just the lines relevant to installing Smarty. First, we define an absolute path to the Smarty directory:

define('SMARTY_PATH', INCLUDE_PATH.'smarty'.DS);

Next, we import the Smarty class:

require_once(SMARTY_PATH.'libs'.DS.'Smarty.class.php');

Finally, we instantiate Smarty and initialize a few key attributes. Notice, that I’ve pointed Smarty’s template directory to our existing VIEW_PATH, so no need to move our existing view files located in includes/views.

$smarty = new Smarty();
$smarty->setTemplateDir(VIEW_PATH);
$smarty->setCompileDir(SMARTY_PATH.'templates_c');
$smarty->setCacheDir(SMARTY_PATH.'cache');
$smarty->setConfigDir(SMARTY_PATH.'configs');

Naming Convention

Smarty brands templates with .tpl extensions to clearly differentiate between PHP files and Template files. So, I simply renamed all views from file.view.php to file.tpl:

Templates

For the sake of comparison, let’s do a side by side comparison between one of our old PHP views and our new Smarty views. Let’s start out with the List view which is responsible for displaying a list of all blog posts.

PHP View:

<?php require_once(VIEW_PATH.'header.inc.php'); ?>

	<?php foreach($posts as $post): ?>

		<h4>
			<a href="read.php?id=<?php 
				echo $post->id;?>"><?php 
				echo $post->title;?>
			</a>
		</h4>

		<p>
			<?php echo $post->content;?>
			<?php echo $post->created;?>
		</p>

	<?php endforeach; ?>

<?php require_once(VIEW_PATH.'footer.inc.php'); ?>

Smarty View:

{include file="header.tpl"}

	{foreach $posts as $post}
			
		<h4>
			<a href="read.php?id={$post->id}">{$post->title}</a>
		</h4>
		
		<p>
			{$post->content}
			{$post->created}
		</p>
		
	{/foreach}

{include file="footer.tpl"}
  • At a quick glance, there’s no doubt that the Smarty view is cleaner.
  • To display the contents of a variable using php we need to open php tags, echo the variable, and close the php tags. We could simplify this statement using PHP short tags, but short tags violate most best practices, so let’s assume they’re not an option. Even so, the Smarty approach is even cleaner than short tags.
  • To display a variable’s contents using Smarty we simply wrap the variable name in curly braces: {$foobar}. Notice how Smarty’s approach really cleaned up our anchor tag linking to the blog post’s title.
  • Next, we compare iteration. Smarty uses {foreach $posts as $post}. I guess Smarty’s opening tag is wee-bit cleaner/readable, but not by much. Same argument could be made for the iterator’s closing tag.
  • Finally, we have the import statements. Smarty uses {include file=”header.tpl”}. Smarty required us to configure a template path so it facilitates the process of importing files since Smarty already knows where to look. So again, yes, the Smarty approach once again results in a cleaner, more readable view.

So, which is better? Well, what bugs me about this whole sales pitch is the notion of a designer-friendly syntax and a true separation of application logic and presentation logic. When I look at the views above, I don’t see an absence of application logic, I just see an absence of PHP. Yes, Smarty’s syntax is arguably cleaner, but it’s still a syntax that needs to be learned. I don’t know that syntax is the barrier to entry for designers. I think any barriers may be more conceptual than practical. Does a designer look at PHP’s syntax and cringe? I don’t know, but I can say that if a designer understands the concept of iteration, I don’t think PHP’s syntax is any more or less daunting than {foreach $posts as $post}. Regardless, let’s take a look at the remaining two views for the Simple Blog application.

Here’s the Read view responsible for displaying a single blog post:

{include file="header.tpl"}

	<h3>{$post->title}</h3>
	
	<p>
		{$post->content}
		{$post->created}<br />
		<a href="update.php?id={$post->id}">Update</a>
		<a href="delete.php?id={$post->id}" 
			onClick = "javascript: return confirm
			('Are you sure you want to delete?');">Delete</a>
	</p>

{include file="footer.tpl"}

Here’s the Upsert view responsible for displaying an HTML form for creating or editing blog posts:

{include file="header.tpl"}

	<form method="POST" action="{$smarty.server.REQUEST_URI|escape:'html'}">

		<p>						
			<label for="title">Title</label><br />
			<input id="title" name="title" type="text" 
				value="{$title|escape:'html'}" autofocus/></p>

		<p>
			<label for="content">Content</label><br />
			<textarea id="content" name="content"
				>{$content|escape:'html'}</textarea></p>
		
		<p>
			<input type="submit" /></p>

	</form>

{include file="footer.tpl"}

In conclusion, the Smarty Template Engine does clean up our views, but at what cost? Smarty needs to be installed, configured, and, most importantly, the new syntax needs to be learned. So, the real question is, what’s the performance penalty we have to pay for a slightly cleaner view? From my tests, Smarty is about 3 to 5 times slower than the native PHP applications we’ve developed so far. So, is it worth it? I say, not. I don’t think the advantages offered by Smarty outweigh the performance penalty.

Next

Shifting gears! Porting Simple Blog to CodeIgniter.
Simple Blog – Example 8

Download

You can download the source code for each example at box.net.
Download Source

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s