November 2008
Monthly Archive
Monthly Archive
admin 01 Nov 2008 | : PHP, Web Design & Development
When developers talk about application development they often spout things like
“When developing an application it is beneficial to separate business logic from the presentation logic”
Which all sounds very technical and intellectual, but what are they going on about when they say things like this?
Imagine a simple website. Three pages liked together by hypertext links. Each of the pages contain text and images hard coded as HTML and the files have a .html extension. There’s no processing behind the scenes, no PHP/ASP or Java, the pages content never changes. These are called static pages. It would be fair to say that this website is almost completely made up of presentation logic. Logic, or code concerned with display and not processing any information.
Now, imagine a PHP scrpt that a form on this website posts it’s information to when someone clicks the submit button. Let’s call it ‘process_form.php’, and lets say this form takes the information posted to it, checks the information is usable, and then redirects you to another page depending on what you entered in the form. This processing of information would be an example of business logic.
Along comes templating…
Templates allow you to seperate your static content from your processing. This way, you could easily change your static content without worrying about the processing code getting in the way and vice versa.
A simple HTML file could look like this:
If we wanted to output PHP in this file we could do something like this:
This would be an example of single-tier, or fused logic. Which makes it difficult to just change our HTML because the HTML and PHP are intertwined in a single layer. Say we created a template file of our original HTML file that looked like this and gave it the extension .tpl
In this example we have replaced the content withcontent placeholders that we can reference later on.
Now, we can produce a simple PHP function that will replace the placeholders with our content after our PHP business logic layer has finished with it. The function may look something like this:
$template = file_get_contents($template);
foreach ($array as $key=>$value){
$template = str_replace(’{’.strtoupper($key).’}',$value,$template);
}
echo $template;
}
This way, from our PHP business logic layer, we can easily produce our presentation layer with any data we like without having to alter the template in any way. An example of calling our template from the business logic layer would be something like this: