Why use it?
also available in Portuguese
One of Smartys primary design goals is to facilitate the separation of
application code from presentation. Typically, the application code contains
the business logic of your application, written and maintained in PHP code.
This code is maintained by programmers. The presentation is the way your
content is presented to the end user, which is written and maintained in
template files. The templates are maintained by template designers.
At its most basic function, the application code collects content, assigns it
to the template engine and displays it. The content might be something like
the headline, tagline, author and body of a newspaper article. The application
code has no concern how this content will be presented in the template. The
template designer is responsible for the presentation. They edit the template
files, adding markup and bringing it to completion. This typically involves
things like HTML tags, cascading style sheets and other tools provided by the
template engine.
This paradigm serves several purposes:
*) Designers can't break application code. They can mess with the templates
all they want, but the code stays intact. The code will be tighter, more
secure and easier to maintain.
*) Errors in the templates are confined to the Smartys error handling routines,
making them as simple and intuitive as possible for the designer.
*) With presentation on its own layer, designers can modify or completely
redesign it from scratch, all without intervention from the programmer.
*) Programmers aren't messing with templates. They can go about maintaining the
application code, changing the way content is acquired, making new business
rules, etc. without disturbing the presentation layer.
*) Templates are a close representation of what the final output will be, which
is an intuitive approach. Designers don't care how the content got to
the template. If you have extraneous data in the template such as an SQL
statement, this opens the risk of breaking application code by accidental
deletion or alteration by the designer.
*) You are not opening your server to the execution of arbitrary PHP code. Smarty
has many security features built in so designers won't breach security,
whether intentional or accidental. They can only do what they are confined to
in the templates.
Although application code is separated from presentation, this does not
necessarily mean that logic is separated. The application code
obviously has logic, but the templates may have logic based on the
condition that it is for presentation only. For example, if the
designer wants to alternate table row colors or upper-case some assigned
content, they can. This is presentation logic, something the programmer should
not be concerned with. How often have you had some presentation displayed in a
single column and then you wanted it in two or three columns, so the
application code needs adjusting to accomodate this? A better approach is to
assign the content in one single array and let the template handle the
presentation. This will simplify your application and keep your templates
flexible. Smarty supplies the tools to handle this kind of situation.
This doesn't mean that Smarty prevents you from putting application logic
in the template, you have to have a bit of self discipline. Here is an example
of embedding business logic in the template (that's right, avoid doing this if
at all possible):
{if $smarty.session.user and ( $user_type eq "editor" or $user_type eq "admin" )}
<input type=checkbox name=edit value="y"> edit <br>
{/if}
|
The logic checks if the user is logged in and they are either an editor or
administrator, then they are allowed to edit this so the edit checkbox shows
up. That is logic that belongs in the application code. The template doesn't
care about what credentials this user has, it just needs to know if the edit
box is displayed or not! So let's look at a more suitable approach:
{if $edit_flag}
<input type=checkbox name=edit value="y"> edit <br>
{/if}
|
It is up to the application programmer to assign the $edit_flag, a simple and
easy-to-understand variable in the template. This way the template is no longer
relying on your underlying data structure. If the format of the session data
structure ever changes, nothing needs to be adjusted in the template.
Now lets look at a few things you can do with Smarty. One thing it can do is
custom functions. These are tags in the template that execute a certain task.
Example:
{html_image file="masthead.gif"}
|
Here we have a function called "html_image". This function takes the image given in
the "file" attribute and does all the work necessary to come up with the
following HTML code:
<img src="masthead.gif" border="0" height="48" width="256">
|
The image function did the chore of figuring out the height and width and
supplying the default border flag. Of course you could just use the static HTML
tag in the template instead, but this demonstrates how a custom function can be
utilized to simplify a very common task. The designer can focus on design and
less on the technical stuff. Furthermore, if the designer decides to drop in a
different size masthead image, the template does not need adjusting.
html_image is a function that comes with Smarty. You can also make your own
custom functions. Here's another example of what one might look like:
{html_link type="article" id="abc123" text="Fire takes out Hotel"}
|
This is using a custom function called "html_link". It comes up with the
following HTML code:
<a href="/display_article.php?id=abc123">Fire takes out Hotel</a>
|
What does this accomplish? For one, the designer does not need to be concerned
with the format of a URL to an article. With hard-coded URLs, what happens if
one day the programmer decides to clean things up, and changes the URL syntax
from /display_article.php?id=abc123 to /ART/abc123 ? We
would have to edit every template with an article URL. This is just another
example of how a template function can make templates easier to maintain.
Now for a bit on programmers and templates. Earlier it was mentioned that the
programmer has no care for what the templates do with the content. At a
conceptual level this is true, but in the real world you are not going to expect
the template designer to have to construct all the templates out of thin air.
After all, the business logic does determine what content is assigned to the
templates. So, the programmer will typically setup skeleton templates for the
designer to start with. This usually contains the raw elements such as content
variables and section loops, and maybe a few simple markup tags so they don't
start with the content in a big mess. Here is an example of a skeleton template
that loops through a list of articles and displays them in a table:
<table>
{section name=art loop=$article}
<tr>
<td>{$article[art].headline}<td>
<td>{$article[art].date}<td>
<td>{$article[art].author}<td>
</tr>
{/section}
</table>
|
The output may look something like this:
<table>
<tr>
<td>How the west was won<td>
<td>Dec 2, 1999<td>
<td>John Wayne<td>
</tr>
<tr>
<td>Team loses, Coach quits<td>
<td>Feb 2, 2002<td>
<td>John Smith<td>
</tr>
<tr>
<td>Gourmet Cooking<td>
<td>Jan 23, 1954<td>
<td>Betty Crocker<td>
</tr>
</table>
|
Now for some common questions:
Why use templates at all? What is so
tough about writing <? echo $title; ?> instead of
{$title}?
Making things easier to read wasn't a design goal, but more of a side effect.
Using templates has huge benefits, many of which have been explained above.
Since we are in a template environment anyways, {$title} is less
extraneous than <?php echo $title; ?>, especially when you start
looking at it in long pages of content, so it was pretty evident that a simpler
syntax helps to make templates easier to read and maintain.
Template take time to parse, making applications much slower.
That may be true in some cases, but with Smarty it is no slower than executing
a PHP script. On the first execution of a template, Smarty converts the
template files into PHP scripts (called template compiling.) Thereafter, the
PHP script is just included. Couple this with a PHP accelerator and you truly
have a fast templating environment with minimal overhead.
Smarty is too complicated, how can it be that fast?
Smarty's core is pretty lean considering what it is capable of. Most of its
functionality lies in plugins. The plugin architecture is designed so that
only the required plugins are loaded on demand. With this framework, adding
even hundreds of new plugins will not affect performance. This makes Smarty
fast, scalable and flexible.
Smarty also has caching features that can dynamically refresh and keep portions
of the page uncached at your liking. Caching stores the output of the
compiled templates, saving the need to execute them on each invocation.
All this talk about accelerators, how does Smarty run without one?
Actually it runs pretty well without one. Smarty does not require an
accelerator, but the template files themselves will take advantage of one,
something that is unique to Smarty (AFAIK). If you don't have an accelerator,
template execution isn't as fast but not slow by any means since they aren't
parsed! You also retain all the other benefits and features of Smarty. Also,
since accelerators are freely available there isn't really an excuse to not be
using one. They'll help performance with all PHP apps, using Smarty or not.
How can it be easier to maintain?
Some things can't be explained, but only experienced :-) The benefit of
separation of the application logic from the presentation cannot be stressed
enough. Smarty also has some nice error handling features and a built-in
debugging console so you can see the template heirarchy and assigned variables
at a glance. Adding custom features to Smarty is as easy as dropping them
in the plugin directory and mentioning them in the template.
The template tags are not XML based, My editor doesn't like it.
The {} delimiters are just a default, they are easy to discern among HTML tags.
If you don't like them, change your delimiters to <% %> or maybe something
more XMLish like <smarty: > There are also lots of user contributions for
dreamweaver and the like, give them a look in the contribs area.
That's Smarty in a nutshell, hopefully you can add it to your arsenal of tools
for web application building. To really learn more, read the manual top to
bottom, join the forums and see what people are discussing.
|