php - 使用逻辑和 html 分离从数据库中列出帖子
问题描述
我想知道如果从数据库中列出帖子,是否有一种方法可以完全分离逻辑和 HTML(没有用于实践和学习目的的 OOP 或模板引擎),目前,代码如下所示:
<!--TEMPLATE:-->
<?php require_once(HEAD); ?>
<body>
<?php require_once(HEADER); ?>
<?php require_once(BANNER); ?>
<!-- Main Content (S) -->
<main class="container">
<?php while($row = mysql_fetch_assoc($result)): ?>
$postImg = $row["post_img"];
$postAuthor = $row["post_author"];
$postTitle = $row["post_title"];
<div class="col">
<div class="card shadow-sm">
<img class="card-img-top" src="<?= $postImg ?>" alt="Card image cap">
<div class="card-body">
<p class="card-text">
<small class="text-muted"><a class="fw-bold" href=""><?= $postAuthor ?></a></small>
</p>
<h5 class="card-title mb-3"><?= $postTitle ?></h5>
<div class="d-flex justify-content-between">
</div>
</div>
</div>
</div>
<?php endwhile; ?>
</main>
<!-- Main Content (E) -->
<?php require_once(FOOTER); ?>
<?php require_once(JS_FILES); ?>
</body>
</html>
变量:$postImg
, $postAuthor
,$postTitle
使用数据库中的数据设置。目前,列出帖子的逻辑与HTML帖子模板发生在同一个地方,我有一个想法,我将这个帖子HTML移动到不同的模板文件,并listPosts()
通过在循环的每次迭代中包含它来在函数中使用它。
主要问题:有没有办法将这篇文章的 HTML 代码留在当前文件中,并以某种方式将其与所有结果集行一起循环?
解决方案
当前的方法是一种很好的做法,因为这就是人们通常将 PHP 与 HTML 结合使用的方式。
您有四个选择:
- 要么遵循 MVC 架构模式
- 使用模板引擎
- 仅将您的 HTML 保存在单独
php
的文件中并包含在逻辑文件中。 - 您的
php
文件具有逻辑,但响应是从客户端提供给 AJAX 调用的,该调用将基于数据(例如:JSON)进行渲染部分。
第三个选项的示例:
您的数据库查询脚本文件:post.php
<!--TEMPLATE:-->
<?php require_once(HEAD); ?>
<body>
<?php require_once(HEADER); ?>
<?php require_once(BANNER); ?>
<!-- Main Content (S) -->
<main class="container">
<?php while($row = mysql_fetch_assoc($result)): ?>
$postImg = $row["post_img"];
$postAuthor = $row["post_author"];
$postTitle = $row["post_title"];
// include template
include 'postView.php';
<?php endwhile; ?>
</main>
<!-- Main Content (E) -->
<?php require_once(FOOTER); ?>
<?php require_once(JS_FILES); ?>
</body>
</html>
你的 html 文件:postView.php
<div class="col">
<div class="card shadow-sm">
<img class="card-img-top" src="<?= $postImg ?>" alt="Card image cap">
<div class="card-body">
<p class="card-text">
<small class="text-muted"><a class="fw-bold" href=""><?= $postAuthor ?></a></small>
</p>
<h5 class="card-title mb-3"><?= $postTitle ?></h5>
<div class="d-flex justify-content-between"></div>
</div>
</div>
</div>
推荐阅读
- delphi - Delphi 初始化记录的常量数组
- linux - 当我在同一文件夹中重命名具有目录名称的文件时会发生什么?
- python - vim“语法集群”突出显示如何工作?
- python - 如何记录按键输入之间的延迟?
- powershell - EWS 如何使用 powershell 获取子文件夹
- python - 如何打印 scikit learn 安排的作业数量?
- libvirt - virt manager - 如何在使用 vnc 时防止鼠标捕获
- flutter - 为什么 Google Distance Matrix Api 返回无效的请求状态?(使用颤振)
- php - 尝试在 int 上读取属性“电子邮件” - Laravel 8
- python - python Discord Bot如何将消息从一个通道发送到另一个通道