3
\$\begingroup\$

I have the following code:

<div id="page-content">
<div class="container-fluid">
    <div class="row">
        <div class="col-lg-11">
            <div id="featured_users></div>
        </div>
    </div>
    <div class="row">
        <div class="col-lg-11">
            <h1> Visitors </h1>
            <?php while($visitor = $visitors->fetch_object()) { ?>
            <?php $time = $visitor->time; ?>
            <?php $visitor = new User($visitor->viewer_id); ?>
            <?php 
            $this->insert('visitors/visitor',[
            'id' => $visitor->id,
            'profile_image' => $visitor->profile_image,
            'name' => $visitor->name,
            'time' => $time->convertToAgo($time);
            ]); 
            ?>
            <? } ?>
        </div>
    </div>
</div>
</div>

I've been trying to think of a way to better separate the logic from the presentation. I'm already using a template engine (Plates, native php templating), this code is from one of my template files. However, as it stands, it won't easy for anyone who has no understanding of PHP to edit my template file without getting confused with all of the PHP code.

Can anyone help me with ideas on the way to do this logic/presentation separation?

\$\endgroup\$

1 Answer 1

1
\$\begingroup\$
    <?php
    // this code goes into your controller
    $visitor_rows = [];

    // lets do all the hard work here
    while($visitor = $visitors->fetch_object()) {
        $time = $visitor->time;
        $visitor = new User($visitor->viewer_id);
        $visitor_rows[] = [
            'id' => $visitor->id,
            'profile_image' => $visitor->profile_image,
            'name' => $visitor->name,
            'time' => $time->convertToAgo($time),
        ]);
    }

    // the template only needs to know about $visitor_rows now
?>


<!-- the template is now a lot simpler to follow and understand -->
<!-- i prefer the foreach: endforeach; loop syntax when embedded in html -->
<div id="page-content">
    <div class="container-fluid">
        <div class="row">
            <div class="col-lg-11">
                <div id="featured_users"></div>
            </div>
        </div>
        <div class="row">
            <div class="col-lg-11">
                <h1> Visitors </h1>
                <?php foreach ($visitor_rows as $row): ?>
                    <?= $this->insert('visitors/visitor', $row) ?>
                <?php endforeach ?>
            </div>
        </div>
    </div>
</div>
\$\endgroup\$
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.