Web Development

Template Driven PHP Architecture

Introduction to using templates and PHP

PHP is an open source and license free language. PHP can be optimized to suit the requirements of different users. The optimization we speak of is possible by either including code snippets downloaded from online communities or by reusing the code once used before. This helps in promoting reusability. The benefits offered by this method include reduced development time and a decrease in testing time.

The above-mentioned benefits can be availed, using a TEMPLATE. A template is nothing but a HTML layout capable of including a PHP code, which is stored in a File.

Why do you need a template?

Classic programmer and the designer scenario:

Designers speak of languages as HTML and CSS, and programmers contemplate of PHP and SQL amongst others. Hence design and programming are two different aspects. Design focuses primarily on presentation, and programming focuses on business logic and logical implementation. Diversifying the concept of designing from programming leads to RAD (Rapid Application Development).

Often in a business scenario the need occurs to change the server side script. PHP makes things easy for a programmer to change the logic, without distorting the underlying design. Changes to presentation logic and design require designers to change to their necessary files, which, without a templating system, may also contain server-side code like PHP.

From the designers end, he makes changes to the website templates, using a simple templating language, to access data from the business logic layer. In short, a templating engine separates the business logic (programming) (PHP) from the design (HTML), allowing designers and programmers to interoperate more effectively.

Given the importance of website templating, there are many options from which to choose a template system implementation. Many individual members of the Open Source software development community have contributed simple and functional versions of PHP-based templating systems. Some are more suited for particular purposes than others. You may have a templating system in place, having an application programming interface (API), whether via function calls on included libraries or method invocation on various template-related objects.

A case study

Managing a newspaper site.

Consider an ideal scenario where the application developer and designer have clearly demarcated portfolios.

For example, let’s say you are creating a web page that is displaying a newspaper article. The article headline, tagline, author and body are content elements, they contain no information about how they will be presented. They are passed into the Template engine by the application, and then the template designer edits the templates and uses a combination of HTML tags and template tags to format the presentation of these elements (HTML tables, background colors, font sizes, style sheets, etc.)

One day the programmer needs to change the way the article content is retrieved (a change in application logic.) This change does not affect the template designer; the content will still arrive in the template exactly the same. Likewise, if the template designer wants to completely redesign the templates, this requires no changes to the application logic. Therefore, the programmer can make changes to the application logic without the need to restructure templates, and the template designer can make changes to templates without breaking application logic.

Method

To use a mechanism that enables the coders/designers to include functionality, which is defined elsewhere. This method allows cutting down the drudgery of re-iterating already existing functionality. This has eventually lead to the concept of TEMPLATES.

The HTML file

It is always irritating to “copy and paste” large portions of PHP code in their HTML Design. But here is an alternative, which could be elaborated easily.

We will have no problem putting HTML-comments: “<!– This is a HTML comment line –>” in our pages. If these designers could put HTML-comments at the places where our PHP code would appear then we could provide scripts to insert PHP codes in them.

In the places where rows of data will be display dynamically (based on database records), we will get them to denote them with “HTML-comment” tags:

“<!–START_ROW–>” and “<!–END_ROW–>”.

TEMPLATE.html

this code would be for generating an ADDRESS BOOK entry

	<table>
        <tr>
          <td> <b>Name </b></td>
          <td> <b>Address</b></td>
        </tr>    

        <!--START_ROW-->
        <tr>
          <td> <!--NAME-DATA--> </td>
          <td> <!--ADDRESS-DATA--> </td>
        </tr>
        <!--END_ROW-->

	</table>

The PHP file

As Coders we need to prepare a script that displays the Address book entries as such:

handler.php

<?php

1:     $template_filename = "TEMPLATE.html";
2:
3:     ..... database extraction codes (omitted) ....
4:
5:/*============================ */
6:/*=======Replacement Rules === */
7:/* =========================== */
8:
9:      $replacement_rules = array (
10:                                 array ("<!--NAME-DATA-->", "0"),
11:                                 array ("<!--ADDRESS-DATA-->", "1")
12:                                );
13:
14: /* ========================= */
15:
16:     $n_fcontents = template_parser ($template_filename, $replacement_rules, $recordset_array);
17:     while (list ($line_num, $line) = each ($n_fcontents))
18:     {
19:        echo "$line";
20:     }

?>

Replacement rules here may refer to a validation criteria or any control mechanism that specifies the content of the address book.

What the above script does is to set rules to display our database-retreived record fields in appropriate columns in the HTML tables. These rules will be stored in $replacement_rules array as defined above.

The elements of $replacement_rules array simply let our script know how to “fill in the blanks”.

The variable

$recordset_array is a 2-dimension array that contains records, which we retrieved from database.

+———————————+

| Alvin | Block 112 Bedok Road |

+———————————+

| Robert | 23 Livingstone Road |

+———————————+

:

:

+———————————+

| John | 556 Everton Park Road |

+———————————+

Line 10 (and line 11) of the code simply is a “rule” that instructs the PHP script to replace occurrences of the string <!–NAME-DATA–> with FIELD 1 (array is “zero-based”) of the recordset provided in the $recordset_array array

All the work will then be performed by the PHP function: template_parser. The detailed workings of template_parser function is as follows :

Function template_parser
function template_parser ($template_filename, $replacement_rules, $recordset_array)
{
   $START_FLAG = 0;
   $start_anchor=0;
   $end_anchor=0;
   $res_arr="";
   $fcontents = file (TEMPLATES_PATH . $template_filename);
   while (list ($line_num, $line) = each ($fcontents))
   {
      if ($START_FLAG == 0)
      {
         if (ereg ('<!--START_ROW-->', $line))
         {
            $START_FLAG = 1;
            $start_anchor = $line_num;
         }
      }
      else
      {
         if (!ereg ('<!--END_ROW-->', $line))
         {
            $res_arr .= $line;
         }
         else
         {
            $START_FLAG = 0;
            $end_anchor = $line_num;
         }
      }
   }

   /* Build String-Replacement Rules ... */
   $tmp_res_arr = "";
   $n = count($data_array);

   for ($x=0; $x<$n; $x++)
   {
      $tmp = $res_arr;
      for ($y=0; $y<count($replacement_rules); $y++)
      {
         $a = $replacement_rules[$y][0];
         $b = $replacement_rules[$y][1];

         if (ereg ("<!", $a))
         {
            $data_array[$x][$b] = stripslashes ($data_array[$x][$b]);
            eval ("\$tmp = str_replace (\"$a\", \$data_array[\$x][$b], \$tmp);");
            $tmp = stripslashes($tmp);
         }
      }
      $tmp_res_arr .= $tmp;
   }
   $res_arr = $tmp_res_arr;

   /* Re-constructing the file-contents ... */
   $n = count($fcontents);
   for ($x=0; $x<$n; $x++)
   {
      $y = $start_anchor + ($x - $end_anchor) ;

      if (($x >= $start_anchor) and ($x < $end_anchor))
      {
         if ($n_fcontents[$start_anchor] == "")
            $n_fcontents[$x] =  $res_arr;
      }
      elseif ($x > $end_anchor)
         $n_fcontents[$y] = $fcontents[$x];
      else
         $n_fcontents[$x] = $fcontents[$x];
   }

   return ($n_fcontents);
}   // end function template_parser

What the above does is to “reproduce” the HTML codes surrounded by both HTML-comment tags :

<!–START_ROW–> and <!–END_ROW–>

as many times as the number of rows found in the $recordset_array array, yet with the intelligence to replace data fields (columns of $recordset_array array) in places defined in the $replacement_rules array without affecting the original HTML formatting.

When all the necessary replacements have been done, the entire HTML page will be “echoed” out by PHP.

What happens when a PHP page is invoked

Browser basically interprets HTML where as PHP is a parsed/compiled by an application server. When ever a request for a PHP page is transferred to the Application server, which could be mainly APACHE. There the parser skips the content included in HTML tags and parses the contents included between <?php ?> tags. PHP code is substituted by the result.

Next the browser displays the contents included in HTML tags, with their respective styling.

About the author

Written by Inforlinx .

If you found this post useful you may also want to check these out:

  1. Test Driven Development
  2. Do Not Reassign the Object Reference of a Locked Object
  3. Publishing Newsletters Using PHP & MySQL – 4
  4. Choosing The Right Server-Side Scripting Language
  5. How To Send Email With Perl, Part I
  6. Client and server-side templating with Velocity