Jun 15, 2009

Three layers of seperation

Data, Logic and Presentation

When building an application(i.e. something) in PHP it is very easy to fall into the pit of putting everything in one big file.
Usually starting with a database connection:

$connection = mysql_connect("localhost", "USER", "PASSWORD");
mysql_select_db("DATABASE", $connection);

$result = mysql_query('SELECT * FROM people');
$row = mysql_fetch_assoc($result);

continue with some logic:

$people = array('Joe', 'Marry', 'Tim', $row['personName']);

and put some presentation:

echo 'Hello'.$people[0];

Then some more data, and more logic and more presentation.
All in one big mess.

So, how do we clean this mess? Using the three layers of seperation.
DATA belongs in one(or more) file(usually a class).
LOGIC belongs in a different file(usually also a class).
PRESENTATION belongs in a template of some kind.

Suggestion
Start your file with a:

require_once("MyData.class.php");
$oData = new Data;
require_once("MyLogic.class.php");
$oMyLogic= new MyLogic;

require_once("MyPresentation.class.php");
$oMyPresentation = new MyPresentation;

Continue with:

$theData = $oData->getTheData();
$theImprovedData = $oMyLogic->doTheMath($theData);
$oMyPresentation->doThePresentation($theImprovedData);


Benefits:
The Designer (see post about him later) can mess around with his design without disturbing the programmer. If there is a bug, it is simple to see whose job it is to fix it.
Managing you application is much easier.
Reusing code is doable.
UpScaling your application is doable.

Recommended tool of trade:
SMARTY (A PHP template engine):
http://www.smarty.net/

No comments:

Post a Comment