Main Content

Separating program and artwork in PHP - easier maintainance, and better for the user

Archive - Originally posted on "The Horse's Mouth" - 2011-12-05 23:16:10 - Graham Ellis

I can code reasonably well. But my graphic design sucks. And both skills are needed for even a simple web data entry form, or a small application.

Using the PHP "bull at a gate" approach, both business logic (the code) and look and feel (the graphic art stuff) can be written into a single file, but it rapidly gets had to manage both elements together, and some sort of separation into two files - which can be maintained by different people, on a different maintainance cycle, makes sense.

During last week's PHP course, I split a really simple example across two files to show how the concept of spliiting in this way starts in practise.

Firstly, a "template file" is written - that's the HTML, but with a unique marker which says "this is where the result of running the code goes". I've chosen to use the string %result% as this marker - it's easily recognised, unlikely to ever really be needed in the template, and can start to form a pattern when I have a whole array of markers to be replaced. Here's part of the template showing it:

  <h1>Multiplication tables</h1>
  %result%
  <hr />


Second, in the business logic - which is a pure PHP file without any HTML code at all, I do NOT use any print or echo calls, but rather produce variable(s) containing the programatically changing element of the page. In my example, I've used the very unimaginative name $string for this variable. Then at the end of the code, I read in the template, substitute the %result% string for the contents of $string, and output the result. Here's the extra code for that:

  $stuff = file_get_contents("t2.xxx");
  $stuff = preg_replace("/%result%/",$string,$stuff);
  print ($stuff);


This principle can be extended to include multiple fill in fields using an array and a loop of preg_replacees. And extended further to separate out a function to do the actual template completion (common code shared between lots of applications). And extended still further to a mulipage, session based application which shares the same template between each of its pages ... giving an application that's easy to maintain, and friendly and familiar to use. Truly, this example is the start of something good - and you should start as you mean to carry on.

Source of the template file [here]
Source of the business logic [here]
And, yes, I'm a programmer. The code is reasonable. Look and feel naff!




These ideas are introduced on our Learning to program in PHP course, and the alternative PHP Programming course for delegates who have prior programming experience. They are further developed on our PHP Techniques Workshop which shows interemediate PHP delegates how to make the very best of the language and system.