How I separate logic from presentation?

后端 未结 2 529
攒了一身酷
攒了一身酷 2021-01-03 05:25

Normally I am developing website and coding PHP and HTML something like this -

while (mysqli_stmt_fetch($stmt)) {      
    // Cre         


        
2条回答
  •  北荒
    北荒 (楼主)
    2021-01-03 05:58

    How I separate logic from presentation?

    Separate it.

    Though it is called business logic from presentation logic separation. You have logic in both layers. The name says it all:

    • perform your "logic" first
    • then turn to "presentation."

    Taking your example it have to be something like this

    $res  = $stmt->get_result();
    $data = array();
    while ($row = mysqli_fetch_assoc($res)) {      
        $data[] = $row;
    }
    

    though I would use some more intelligent approach to get data from database, something like this:

    $data = $db->getArr("SELECT ...");
    

    then repeat all the steps for all the database or other other services interaction. Your goal is to have all the data ready that business logic have to supply. Then your business logic ended and you can turn to presentation.

    You can tell a good separation from the bad one if you can easily interchange template engines (you can't do it with approach from other answer, mind you) - so, particular engine doesn't matter. Let's take a simplest one - PHP

    Create a file called tpl.php and put this code there

    then include this file in your business logic file. Or - better - in some higher level template.

    You can see a good real life example of the approach in this topic

    Using such a separation, you can:

    1. Use power of good editor that can do syntax highlighting and hinting (though I doubt you are using one).
    2. outsource your design to a professional designer.
    3. easily change presentation technology from HTML to AJAX.
    4. use the same engine for the different sites with different appearances.
    5. Implement any number of "themes" or "skins".
    6. Stay alive when adding some rich decorations from either HTML, CSS or JS.

    While all this is just impossible with your current approach or approach from other answer. The idea is separation of matters.

    提交回复
    热议问题
    and so on