многопоточность — класс PHP для создания семантического пользовательского интерфейса с резьбой Комментарии HTML

Я пытался создать Семантический пользовательский интерфейс с резьбой комментариев HTML используя PHP-класс в течение многих часов, но, к сожалению, я не смог этого сделать.

Вот мой текущий класс, который не работал должным образом:

class SemanticUiThreadedComments {

function PrintComments( $comments ) {

/** Comment prepare start */
foreach ( $comments as $k => &$v ) {
if ( $v['comment_parent'] != 0 ) {
$comments[ $v['comment_parent'] ]['children'][] =& $v;
}
}
unset( $v );

foreach ( $comments as $k => $v ) {
if ( $v['comment_parent'] != 0 ) {
unset( $comments[ $k ] );
}
}

/** Comment prepare end */

$html = '';
$html .= '<div class="ui threaded comments">';
$html .= '<h3 class="ui dividing header">'.__( 'Comments','trusty' ).'</h3>';

ob_start();
$this->PrintSingleComments( $comments );
$html .= ob_get_clean();

$html .= $this->reply_form();
$html .= '</div>';

return $html;

}

function indent( $size ) {
$string = '';
for ( $i = 0; $i < $size; $i++ ) {
$string .= '</div>';
}
echo $string;
}

function PrintSingleComments( $comments, $indent = 0 ) {
foreach ( $comments as $comment ) {
echo $this->comment( $comment, 1 );
if ( ! empty( $comment['children'] ) ) {

$this->PrintSingleComments( $comment['children'], $indent + 1 );

}
$div_num = $indent + 1;
$this->indent( $div_num );
}
}

function comment( $comment ) {
ob_start();
echo '<div class="comment" id="'.$comment['comment_id'].'">';
echo $this->avatar();
echo $this->content();
echo ( ! empty( $comment['children'] ))? '<div class="comments">':'</div>';

$html = ob_get_clean();

return $html;
}

function avatar() {
$html = '';
$html .= '<a class="avatar">';
$html .= '<img src="/images/avatar/small/matt.jpg">';
$html .= '</a>';

return $html;
}

function content() {
$html = '';
$html .= '<div class="content">';
$html .= '<a class="author">Matt</a>';
$html .= '<div class="metadata">';
$html .= '<span class="date">Today at 5:42PM</span>';
$html .= '</div>';
$html .= '<div class="text">';
$html .= 'How artistic!';
$html .= '</div>';
$html .= '<div class="actions">';
$html .= '<a class="reply">Reply</a>';
$html .= '</div>';
$html .= '</div>';

return $html;
}

function reply_form() {
$html = '';
$html .= '<form class="ui reply form">';
$html .= '<div class="field">';
$html .= '<textarea></textarea>';
$html .= '</div>';
$html .= '<div class="ui primary submit labeled icon button">';
$html .= '<i class="icon edit"></i> Add Reply';
$html .= '</div>';
$html .= '</form>';

return $html;
}
}

$comments = array(
1 => array( 'comment_id' => 1, 'comment_parent' => 0, 'children' => array() ),
2 => array( 'comment_id' => 2, 'comment_parent' => 0, 'children' => array() ),
3 => array( 'comment_id' => 3, 'comment_parent' => 0, 'children' => array() ),
5 => array( 'comment_id' => 5, 'comment_parent' => 0, 'children' => array() ),
11 => array( 'comment_id' => 11, 'comment_parent' => 0, 'children' => array() ),
17 => array( 'comment_id' => 17, 'comment_parent' => 0, 'children' => array() ),
23 => array( 'comment_id' => 23, 'comment_parent' => 0, 'children' => array() ),
28 => array( 'comment_id' => 28, 'comment_parent' => 0, 'children' => array() ),
4 => array( 'comment_id' => 4, 'comment_parent' => 1, 'children' => array() ),
6 => array( 'comment_id' => 6, 'comment_parent' => 1, 'children' => array() ),
8 => array( 'comment_id' => 8, 'comment_parent' => 2, 'children' => array() ),
9 => array( 'comment_id' => 9, 'comment_parent' => 2, 'children' => array() ),
7 => array( 'comment_id' => 7, 'comment_parent' => 3, 'children' => array() ),
12 => array( 'comment_id' => 12, 'comment_parent' => 7, 'children' => array() ),
13 => array( 'comment_id' => 13, 'comment_parent' => 12, 'children' => array() ),
);

$threaded_comments = new SemanticUiThreadedComments();
echo $threaded_comments->PrintComments( $comments );

Я не хочу никаких ограничений, например, комментарий может иметь десять уровней дочерних комментариев.

Будем очень благодарны за любые предложения о том, как заставить этот класс работать или лучший способ достичь этого.

0

Решение

Я знаю, что это не идеальное решение моего вопроса, и поэтому я не выберу его в качестве ответа, однако это рабочий класс, я попытался сделать это совершенно другим методом, поэтому я переписал свой класс, надеюсь, кто-нибудь найдет это полезным.

Если кто-нибудь в любое время опубликует ответ лучше этого, я выберу его в качестве ответа на мой вопрос, мы публикуем здесь вопросы не только для себя, но и чтобы помочь друг другу.

class Semantic_Ui_Comments_Generator {

private $comments ;
private $user_data ;

function __construct( $comments ) {
$this->comments = $comments;
}

function PrintComments() {

$rest_of_comments = array();

$trusty_comments = $this->comments;

$html = '';
$html .= '<div class="ui threaded comments">';
$html .= '<h3 class="ui dividing header">'.__( 'Comments','trusty' ).'</h3>';

foreach ( $trusty_comments  as $key => $comment ) {

if (  $comment->comment_parent == 0 ) {
$html .= $this->comment( $comment );
} else {
$rest_of_comments[ $key ] = $comment;
}
}

$html .= $this->reply_form();
$html .= '</div>';

$num_rest_of_comments = count( $rest_of_comments );

for ( $i = 0; $i < $num_rest_of_comments; $i++ ) {

if ( empty( $rest_of_comments ) ) {
break;
}

foreach ( $rest_of_comments  as $key => $comment ) {

libxml_use_internal_errors( true );
$dom = new DOMDocument();
$dom->loadHTML( $html );

// get the element you want to append to
$current_comment = $dom->getElementById( 'comments_of_'.$comment->comment_parent );

if ( $current_comment ) {

// create the fragment
$fragment = $dom->createDocumentFragment();

$new_comment = $this->comment( $comment );

// add content to fragment
$fragment->appendXML( $new_comment );
// actually append the element
$current_comment->appendChild( $fragment );

/*
* Clean things up
*/
// remove <!DOCTYPE
$dom->removeChild( $dom->doctype );
// remove <html><body></body></html>
$dom->replaceChild( $dom->firstChild->firstChild->firstChild, $dom->firstChild );

$html = $dom->saveHtml();

unset( $rest_of_comments[ $key ] );
}
}
}

return  $html;
}

function comment( $comment ) {

$this->user_data = get_user_by( 'id', $comment->user_id );

$html = '<div class="comment" id="comment_'.$comment->comment_id.'">';
$html .= $this->avatar( $comment->user_id );
$html .= $this->content( $comment,$this->user_data );
$html .= $this->has_child( $comment->comment_id )? '<div class="comments" id="comments_of_'.$comment->comment_id.'"></div>':'';
$html .= '</div>';

return $html;
}

function has_child( $comment_id ) {
$trusty_comments = $this->comments;

foreach ( $trusty_comments as $key => $comment ) {
if ( $comment->comment_parent == $comment_id ) {
return true;
}
}

return false;
}

function avatar( $user_id ) {
$html = '';
$html .= '<a class="avatar">';
$html .= get_avatar( $user_id ,35 );
$html .= '</a>';

return $html;
}

function content( $comment, $user_data ) {
$html = '';
$html .= '<div class="content">';
$html .= '<a class="author">'.$user_data->user_login.'</a>';
$html .= '<div class="metadata">';
$html .= '<span class="date">'.$comment->date.'</span>';
$html .= '</div>';
$html .= '<div class="text">';
$html .= $comment->comment;
$html .= '</div>';
$html .= '<div class="actions">';
$html .= '<a class="reply">Reply</a>';
$html .= '</div>';
$html .= '</div>';

return $html;
}

function reply_form() {
$html = '';
$html .= '<form class="ui reply form">';
$html .= '<div class="field">';
$html .= '<textarea></textarea>';
$html .= '</div>';
$html .= '<div class="ui primary submit labeled icon mini button">';
$html .= '<i class="icon edit"></i> Add Reply';
$html .= '</div>';
$html .= '</form>';

return $html;
}
}

Обратите внимание, что данные комментариев, которые предполагается ввести в класс, являются массивом объектов, а не ассоциативным массивом, как в вопросе.

Это что-то вроде:

array(7) {
[1] =>
class stdClass#366 (7) {
public $comment_id =>
string(1) "1"public $review_id =>
string(2) "26"public $user_id =>
string(1) "1"public $date =>
string(19) "2016-07-13 00:00:00"public $status =>
string(7) "pending"public $comment =>
string(74) "Lorem Ipsum is simply dummy text of the printing and typesetting industry."public $comment_parent =>
string(1) "0"}
[2] =>
class stdClass#365 (7) {
public $comment_id =>
string(1) "2"public $review_id =>
string(2) "26"public $user_id =>
string(1) "1"public $date =>
string(19) "2016-07-13 02:00:00"public $status =>
string(7) "pending"public $comment =>
string(75) "publishing software like Aldus PageMaker including versions of Lorem Ipsum."public $comment_parent =>
string(1) "0"}
[3] =>
class stdClass#364 (7) {
public $comment_id =>
string(1) "3"public $review_id =>
string(2) "26"public $user_id =>
string(1) "1"public $date =>
string(19) "2016-07-13 08:00:00"public $status =>
string(7) "pending"public $comment =>
string(132) "centuries, but also the leap into electronic typesetting, remaining essentially unchanged."public $comment_parent =>
string(1) "2"}
[5] =>
class stdClass#363 (7) {
public $comment_id =>
string(1) "5"public $review_id =>
string(2) "26"public $user_id =>
string(1) "1"public $date =>
string(19) "2016-07-16 00:00:00"public $status =>
string(7) "pending"public $comment =>
string(207) "It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum."public $comment_parent =>
string(1) "0"}
[6] =>
class stdClass#362 (7) {
public $comment_id =>
string(1) "6"public $review_id =>
string(2) "26"public $user_id =>
string(1) "1"public $date =>
string(19) "2016-07-16 02:00:00"public $status =>
string(7) "pending"public $comment =>
string(207) "It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing"public $comment_parent =>
string(1) "5"}
[7] =>
class stdClass#361 (7) {
public $comment_id =>
string(1) "7"public $review_id =>
string(2) "26"public $user_id =>
string(1) "1"public $date =>
string(19) "2016-07-16 04:00:00"public $status =>
string(7) "pending"public $comment =>
string(207) "It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing."public $comment_parent =>
string(1) "5"}
[8] =>
class stdClass#360 (7) {
public $comment_id =>
string(1) "8"public $review_id =>
string(2) "26"public $user_id =>
string(1) "1"public $date =>
string(19) "2016-07-19 05:00:00"public $status =>
string(7) "pending"public $comment =>
string(139) "containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum."public $comment_parent =>
string(1) "0"}
}
0

Другие решения

Других решений пока нет …

По вопросам рекламы [email protected]