(redirected from Main.KeepCodeAndPresentationSeparate)
On this page... (hide)
Introduction
When I was first starting out writing web applications, back in the days of ColdFusion, it was common practice to intermingle code and presentation. This made for some horrendous coding choices and made maintenance a nightmare. Yet all the examples given were of intermingled code and presentation. When PHP was new, it faired no better. PHP was originally designed to intermingle with HTML code, and many still do this.
Here's an example:
- <div id="div_duration">
- <label for="duration"><?php echo get_vocab("duration");?>:</label>
- <div class="group">
- <input id="duration" name="duration" value="<?php echo $duration;?>">
- <select id="dur_units" name="dur_units">
- <?php
- if( $enable_periods )
- {
- $units = array("periods", "days");
- }
- else
- {
- $units = array("minutes", "hours", "days", "weeks");
- }
- while (list(,$unit) = each($units))
- {
- echo " <option value=\"$unit\"";
- if ($dur_units == get_vocab($unit))
- {
- echo " selected=\"selected\"";
- }
- echo ">".get_vocab($unit)."</option>\n";
- }
- ?>
- </select>
- <div id="ad">
- <input id="all_day" class="checkbox" name="all_day" type="checkbox" value="yes" onclick="OnAllDayClick(this)">
- <label for="all_day"><?php echo get_vocab("all_day"); ?></label>
- </div>
- </div>
- </div>
Really pretty ugly. Still, this was what PHP was meant to do. How to actually extract code from presentation? One good way is the use of templates. Smarty is one great templating system for PHP. With it, you keep all your controller, models, helpers, etc. separate from your views. The views are stored at templates, which are compiled into regular PHP code by the Smarty engine. (Under the hood, the Smarty compiled templates do intermingle presentation and PHP, but the point is it's divorced from the coder).
Using Smarty
Smart is a library that you can install on your sever pretty much anywhere, or you can include it in a directory in your application. There is little to set up to use Smarty, just a couple of directories in your application, and you're all set.
If you do install Smarty somewhere on your server out of the way of your application, make sure PHP can find it. You may need to add the path to the Smarty implementation to your php include path set in php.ini:
- include_path=".:/usr/lib/php:/usr/lib/php/includes:/usr/lib/php/Smarty"
(Note the include_path begins with "." which means it will search the current working directory first for any included/required files.)
Then, in your PHP code (preferably in a config.inc file), you set up the Smarty engine:
- require_once('Smarty.class.php');
- /**
- * Set up Smarty
- */
- $smarty = new Smarty();
- $smarty->template_dir = APP_ROOT . 'templates/';
- $smarty->compile_dir = APP_ROOT . 'templates_c/';
- //debug_var("\$smarty=",$smarty);
(Note: For the APP_ROOT constant, see Getting The Root Of Your Application)
To make Smarty emit the proper HTML codes, you first assign data for the template:
- $smarty->assign('title',"This could be the title of the page");
- $smarty->assign('rows',$rows);
- if (!empty($messages)) $smarty->assign('messages',$messages);
- if (!empty($errors)) $smarty->assign('errors',$errors);
- if (!empty($additional_query_parms)) {
- $smarty->assign('additional_query_string,http_build_query($additional_query_parms));
- $smarty->assign('additional_query_parms',$additional_query_parms);
- }
Then you tell Smarty to display the template:
- $smarty->display('templatename.tpl");
Smarty Templates
Smarty templates have specially designed markup that enables them to process the input and produce the proper display. Standard Smart delimiters are "{" and "}" but these can be changed. One person I know uses "<!--{" and "}-->" as delimiters, presumably so the temp;ates can be validated directly.
A sample tempate looks like this:
- {* index file for application *}
- {include file="header.tpl"}
- {include file="nav.tpl"}
- <div id="content">
- {include file="messages.tpl"}
- {include file="errors.tpl"}
- {if $num_comics > 0}
- <ul>{foreach from=$comics item=comic}
- <li class="comicentry">
- <span class="comictitle">{$comic.name}</span>
- <span class="comicdate">{$comic.comicdate}</span>
- <br />
- <a href="{$comic.uri}"><img src="{$smarty.const.APP_URI_BASE}{$comic.filespec}" alt="{$comic.name} {$comic.comicdate}" /> </a>
- <br />
- <a href="showcomics.php?sid={$comic.subscription_id}{if !empty($additional_query_string)}&{$additional_query_string}{/if}">Show all comics for this subscription</a>
- </li>
- {/foreach}</ul>
- {else}
- <h3>No comics to display.</h3>
- {/if}
- </div>
- {include file="footer.tpl"}
You can see several ideas in there. First of all, notice the use of include files to set up a standard look and feel and navigation around the page.
- header.tpl -- provides a place to put the html head preamble, set javascript libraries, stylesheets, etc.
- nav.tpl -- provides a means for producing standard navigation on the web page
- footer.tpl -- a common footer to end the page. This could include site policy links, copyright info, etc.
- messages.tpl and errors.tpl -- provide a standard mechanism for displaying messages and errors from the application to the client.
- centered in it all is a content div where you can produce your structured output
Other things to notice.
Smarty has control structures in it, so you can do things like loop over an array of values (say, perhaps database records). It also provides if-then-else constructs. There are a few other constructs that make it possible to display just about anything with Smarty, yet Smarty isn't a complicated syntax. Underneath, of course, is PHP, and you can expose Smarty to raw PHP if you desire (but hold onto that thought because you don't want to introduce code back into presentation).
Not using a predefined package
In spite of all that said above about Smarty, PHP itself is actually a templating language. You can accomplish pretty much the same thing in straight PHP and HTML as you can in Smarty, without the overhead of a package. You can keep regular PHP files in a templates or views directory, and include subparts of the template as easily as you can in Smarty. An advantage to rolling your own templates is that you keep total control of the package and don't depend on anyone else's development for your work. Keeping your business logic and data base access separate is still important, and can be done quite handily without resorting to a special template framework.
| Tags: | Categories: Articles |
Recent Changes |
Printable View |
Page History |
Edit Page
Page last modified on April 17, 2012, at 08:59 PM by ImportText?