views:

75

answers:

3

Hi Mates,

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 templates are HTML/CSS of course. My question is, how to solve this issue best (without using a CMS).

greetz, poeschlorn

+2  A: 

Use a Template Engine, e.g. Smarty.

Alternatively just use HTML with embedded php for templates, just be careful not to put too much logic into the template.

Fabian
+1  A: 

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 ?>
<form method="POST">
<input type="text" name="name" value="<?=$row['name']?>"><br>
<input type="hidden" name="id" value="<?=$row['id']?>">
<input type="submit"><br>
<a href="?">Return to the list</a>
</form>
<? include TPL_BOTTOM ?>

and list.php

<? include TPL_TOP ?>
<a href="?id=0">Add item</a>
<? foreach ($LIST as $row): ?>
<li><a href="?id=<?=$row['id']?>"><?=$row['name']?></a>
<? endforeach ?>
<? include TPL_BOTTOM ?>

Though there are plenty of other template engines, of different kinds and ideologies.

Col. Shrapnel
As an onlooker, does PHP code have to exist only in the pages being served, or can it be separated out into something like a supporting class library?
John K
@jdk PHP can include() or require() additional files such as libraries of functions or classes
Mark Baker
+1  A: 

Try an MVC framework like

CodeIgniter: http://codeigniter.com/

or CakePHP: http://cakephp.org/

(Cake has got a steeper learning curve, but does a lot more stuff automagically)

Here's what MVC is about: http://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller

quantumSoup