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?

asked Feb 8, 2018 at 23:55
\$\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>
Your Common Sense
9,1231 gold badge22 silver badges51 bronze badges
answered Feb 9, 2018 at 6:36
\$\endgroup\$
0

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.