gpt4 book ai didi

php - 将 html 与 php 注释类分开

转载 作者:太空狗 更新时间:2023-10-29 14:23:36 28 4
gpt4 key购买 nike

我发现这个类用于使用 php 和 MySQL 的线程评论:

<?php
class Threaded_comments
{

public $parents = array();
public $children = array();

/**
* @param array $comments
*/
function __construct($comments)
{
foreach ($comments as $comment)
{
if ($comment['parent_id'] === NULL)
{
$this->parents[$comment['id']][] = $comment;
}
else
{
$this->children[$comment['parent_id']][] = $comment;
}
}
}

/**
* @param array $comment
* @param int $depth
*/
private function format_comment($comment, $depth)
{
for ($depth; $depth > 0; $depth--)
{
echo "\t";
}

echo $comment['text'];
echo "\n";
}

/**
* @param array $comment
* @param int $depth
*/
private function print_parent($comment, $depth = 0)
{
foreach ($comment as $c)
{
$this->format_comment($c, $depth);

if (isset($this->children[$c['id']]))
{
$this->print_parent($this->children[$c['id']], $depth + 1);
}
}
}

public function print_comments()
{
foreach ($this->parents as $c)
{
$this->print_parent($c);
}
}

}

这适用于这个数组:

$comment = array(  array('id'=>1, 'parent_id'=>NULL,   'text'=>'Parent'),  
array('id'=>2, 'parent_id'=>1, 'text'=>'Child'),
array('id'=>3, 'parent_id'=>2, 'text'=>'Child Third level'),
array('id'=>4, 'parent_id'=>NULL, 'text'=>'Second Parent'),
array('id'=>5, 'parent_id'=>4, 'text'=>'Second Child')
);

结果:

$tc = new Threaded_comments($comment);
$tc->print_comments();

结果是:

Parent
Child
Child Third level
Second Parent
Second Child

这确实有效但是对于定义评论列表(html),我需要将所有 html 代码添加到 private function format_comment($comment, $depth) 中。这不是好方法,我认为需要将 htmlphp class 分开。

编辑:(这是我的显示/打印线程评论页面)

function _comments_($id,$type){
$DB_QUERY = mySqli::f("SELECT id,user,email,message,timestamp,parent_id,rfield_1,rfield_2,rfield_3,rfield_4,rfield_5 FROM " . NEWS_COMMENTS . " LEFT JOIN " . NEWS_REVIEWS . " ON " . NEWS_COMMENTS . ".id = " . NEWS_REVIEWS . ".cid WHERE
pid = ? AND type = ? AND approved = 1 ORDER BY timestamp DESC LIMIT 12", $id, $type);

foreach($DB_QUERY as $row){
$commentdata[] = $row;
}
return $commentdata;
}
$comments_list = _comments_('125','book');
foreach($comments_list as $row){
$comments[] = array(
'id' => $row['id'],
'parent_id' => $row['parent_id'],
'name' => $row['user'],
'text' => $row['message'],
'datetime' => $row['timestamp']
);
}

$tc = new Threaded_comments($comments);
$tc->print_comments();

在我的页面中,线程评论显示为 format_comment 并且有效。如果我需要使用来自 php 类的单独 html 来设计输出。

在这种情况下,我们如何将 html 代码与类分开?!

最佳答案

你是对的。

1) 最简单的解决方案是将数组传递给模板。此模板不包含逻辑,仅包含 html 和 php(例如,foreach 数组)。

2) 为了更好的分离,使用模型- View - Controller 模式:

Simple view of MVC

采用这种分层结构,每一层都有自己的职责。从不在模型和 Controller 中使用 html。仅在模型中查询。

Laravel 和 CodeIgniter 等框架实现了这种模式。

关于php - 将 html 与 php 注释类分开,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32409664/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com