简体   繁体   English

逻辑和标记,HTML和PHP

[英]Logic and markup, html and php

I am learning php. 我正在学习php。 I see that people recommend to separate html and php or logic and markup. 我看到人们建议将html和php或逻辑和标记分开。 But in some specific occasions I am not sure how to do it. 但是在某些特定情况下,我不确定该怎么做。 For readability and maintainability I try to put all the php in a separate file but now I have to download a title from a database and the only way I see is to put this with the rest of the html and with this html and php mixed. 为了提高可读性和可维护性,我尝试将所有php放在一个单独的文件中,但是现在我必须从数据库下载标题,而我看到的唯一方法是将其与其余的html以及html和php混合在一起。 In this specific case, is there a more clean and organized way? 在这种特定情况下,是否有更干净,更有条理的方式? is ok to put this peace of php in the "design" file? 将这种和平的php文件放入“设计”文件中可以吗? can or should I put this php code with the rest of the php? 我可以还是应该把这个php代码与其余的php放在一起?

<?php
include("../../externs/includes/connexio.php");

$result = mysqli_query($con, "SELECT * FROM myTable");

while ($row = mysqli_fetch_array($result)) {
    $id = $row["id"];
    $title = $row["title"];
    $subtitle = $row["subtitle"];
?>  

<div class="title" id="<?php echo $id; ?>"><?php echo $title; ?> </div>
<div class="subtitle"><?php echo $subtitle;?> </div>
<br>

<?php 
}//end while items
?>

First of all I would recommend to read about MVC (Model-View-Controller), you can start at this Wikipedia article: http://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller 首先,我建议您阅读有关MVC(模型-视图-控制器)的信息,您可以从此Wikipedia文章开始: http : //en.wikipedia.org/wiki/Model%E2%80%93view%E2%80% 93controller

For a simple case as the one fro you question, your solution is, in my opinion, the best. 我认为对于一个简单的问题,您的解决方案是最好的。 Anything else would be to add unnecessary complexity. 其他任何事情都会增加不必要的复杂性。

That being said, I will try to use that simple case and offer one possible way to separate logic from presentation with the hope that some basic concepts will become clear from it. 话虽如此,我将尝试使用这种简单的情况,并提供一种可能的方法,将逻辑与表示分离开来,以期一些基本概念将从中变得清晰。

my_controller.php my_controller.php

include("../../externs/includes/connexio.php");

$result = mysqli_query($con, "SELECT * FROM myTable");

$myList = array();
while ($row = mysqli_fetch_array($result)) 
{
    $myList[] = $row;
}

// Now load the view.
include "my_view.php";

my_view.php my_view.php

<?php foreach ($myList as $row ) : ?>

    <div class="title" id="<?php echo $row['id']; ?>"><?php echo $row['title']; ?></div>
    <div class="subtitle"><?php echo $row['subtitle'];?></div>
    <br>

<?php endforeach; ?>

As you see, I just took your code and separated it in what would be business logic and presentation. 如您所见,我只是获取了您的代码,并将其分离为业务逻辑和表示形式。 The idea here is that data to be presented should be generated outside the View. 这里的想法是要呈现的数据应在视图外部生成。 The View should know nothing about how the data was "generated". 视图应该对如何“生成”数据一无所知。

In this example, the View only knows about the variable $myList containing the fields: id, title and subtitle. 在此示例中,视图仅知道包含字段:id,title和subtitle的变量$ myList。 If you ever change databases or decide to fetch data from a file or even a Web service; 如果您曾经更改数据库或决定从文件或Web服务中获取数据,请执行以下操作: you would not have to touch the View at all. 您根本不需要触摸视图。

At the same time, the controller doesn't care about how the View shows the data. 同时,控制器不在乎视图如何显示数据。 Regardless of the source: database, Web service, file, etc; 无论来源如何:数据库,Web服务,文件等; it will always produce an array containing at least the fields expected by the View. 它将始终产生至少包含View期望字段的数组。

The next step to MVC would be to move data manipulation from controller to a model. MVC的下一步是将数据操作从控制器转移到模型。 I won't go there in detail, but this is how the controller would look like: 我不会在那儿详细介绍,但这是控制器的外观:

include "my_model.php";
$myList = fetchData();
include "my_view.php;

The fetchData() function inside the my_model.php file would basically do the same as my_controller.php above. fetchData()内部函数my_model.php文件将基本上做的是一样的my_controller.php以上。

A very debatable and indeed debated issue is whether having any PHP code inside the View is a good practice. 一个非常有争议且确实存在争议的问题是,在View中包含任何PHP代码是否是一种好习惯。 Some argue that other templating languages such as Smarty should be used. 有人认为应该使用其他模板语言,例如Smarty。 My opinion is that changing the syntax by adding another language doesn't change the inevitable fact that you need some logic in the View, otherwise you would be unable to introduce dynamism to your applications. 我的观点是,通过添加另一种语言来更改语法不会改变不可避免的事实,即您需要在View中添加一些逻辑,否则您将无法向应用程序引入动态性。

As you feel more comfortable reading PHP code, you will be able to look into the several frameworks around and see how they do it. 当您阅读PHP代码时更加自在时,您将能够研究周围的几个框架,并了解它们是如何做到的。 One thing they all have in common is that they all have some logic in the presentation layer, whether it is PHP or something else. 它们都有一个共同点,那就是它们在表示层都有一些逻辑,无论是PHP还是其他东西。

Following are the best practices you can follow while mixing PHP with markup. 以下是将PHP与标记混合使用时可以遵循的最佳实践。

(Not a best practice) (不是最佳做法)

1) if for example you have a logic on the top and you wish to generate markup, one not so good way you can do is: 1)例如,如果您在顶部有一个逻辑,并且希望生成标记,那么您可以采取的一种不太好的方法是:

<?php
$query = mysql_query("SELECT id,name FROM table");

while($row = mysql_fetch_assoc($query)){
    $id   = $row['id'];
    $name = $row['name'];
?>

<div>ID:<?php echo $id;?></div>
<div>NAME:<?php echo $name;?></div>

<?php
}
?>

In the above code you have to keep track of the ending curly brace, if your application is complex it can create a problem especially in more then one level of iteration. 在上面的代码中,您必须跟踪结尾的花括号,如果您的应用程序很复杂,则可能会产生问题,尤其是在一个以上的迭代级别中。

2) Good way to do is to make use of PHP tags such as 2)好的方法是利用PHP标记,例如

<?php if(count($array)):?>

    <?php foreach($array as $result):?>

        <div><?php echo result;?></div>

    <?php endforeach;?>

<?php else:?>

    <div>NO results found</div>

<?php endif;?>

Your code has no presentation issues but if it is a complex application then you need to follow best practices. 您的代码没有显示问题,但是如果它是复杂的应用程序,则需要遵循最佳实践。

<?php
$array = array();
$query = mysql_query("SELECT id,name FROM table");

while($row = mysql_fetch_assoc($query)):
    $array[] = $row;
endwhile;
?>

Outside of PHP tag check the count of $array , if there is count then generate markup. 在PHP标记之外,检查$array的计数,如果有计数,则生成标记。

<?php if(count($array)):?>

    <?php foreach($array as $result):?>

        <div>ID<?php echo result['id'];?></div>
        <div>ID<?php echo result['name'];?></div>

    <?php endforeach;?>

<?php else:?>

    <div>NO results found</div>

<?php endif;?>

Using this kind of formatting you can achieve pleasing results. 使用这种格式可以达到令人愉悦的效果。 Try to separate or avoid mixing too much PHP with markup. 尝试分离或避免将过多的PHP与标记混合使用。 If you want your presentation logic to be separated from business logic then I recommend you to use MVC model as it increases readability and maintainability. 如果您希望将表示逻辑与业务逻辑分开,那么我建议您使用MVC模型,因为它可以提高可读性和可维护性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM