Separating Logic/Style in PHP properly

前端 未结 3 552
星月不相逢
星月不相逢 2020-12-11 12:18

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

相关标签:
3条回答
  • 2020-12-11 12:48

    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.

    0 讨论(0)
  • 2020-12-11 12:48

    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

    0 讨论(0)
  • 2020-12-11 12:56

    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.

    0 讨论(0)
提交回复
热议问题