I\'m just wondering what is the best way to separate logic components from the layout in a PHP web project?
The content is stored in MySQL, the logic is PHP and the
Just use some template engine.
The most familiar one is PHP itself.
here is the very basic example of CRUD application:
the logic part doing only data manipulation
mysql_connect();
mysql_select_db("new");
$table = "test";
if($_SERVER['REQUEST_METHOD']=='POST') { //form handler part:
$name = mysql_real_escape_string($_POST['name']);
if ($id = intval($_POST['id'])) {
$query="UPDATE $table SET name='$name' WHERE id=$id";
} else {
$query="INSERT INTO $table SET name='$name'";
}
mysql_query($query) or trigger_error(mysql_error()." in ".$query);
header("Location: http://".$_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF']);
exit;
}
if (!isset($_GET['id'])) { //listing part:
$LIST=array();
$query="SELECT * FROM $table";
$res=mysql_query($query);
while($row=mysql_fetch_assoc($res)) $LIST[]=$row;
include 'list.php';
} else { // form displaying part:
if ($id=intval($_GET['id'])) {
$query="SELECT * FROM $table WHERE id=$id";
$res=mysql_query($query);
$row=mysql_fetch_assoc($res);
foreach ($row as $k => $v) $row[$k]=htmlspecialchars($v);
} else {
$row['name']='';
$row['id']=0;
}
include 'form.php';
}
?>
and two simple templates responsible for output,
form.php
include TPL_TOP ?>
include TPL_BOTTOM ?>
and list.php
include TPL_TOP ?>
Add item
foreach ($LIST as $row): ?>
- =$row['name']?>
endforeach ?>
include TPL_BOTTOM ?>
Though there are plenty of other template engines, of different kinds and ideologies.