jpwco jpwco - 2 months ago 7
PHP Question

Where should HTML be rendered in Object-Oriented PHP design?

Using Object-Oriented PHP, where should HTML be rendered?

The business processes include several actions to maintain customer records.

Should the rendering of each business process get a separate PHP file? ie. viewCustomerTransactions.php?

Where should code like this reside?

$custTrans = Customer.getTransactions();

foreach ($custTrans as $ct){
$amount = $ct[0];
$date = $ct[1];
$product = $ct[2];

echo '<div class="custTrans">';
echo '<span class="custTransAmount">'.$amount.'</span>';
echo '<span class="custTransDate">'.$date.'</span>';
echo '<span class="custTransproduct">'.$product.'</span>';
echo '</div>';
}


Perhaps an MVC framework like codeigniter would be better?

Answer

I'm still figuring out what's the best way to keep php and layout seperate without too much fuzz. For the moment I really like the include-templating approach, beacause it's so simple and has no restrictions.

So, for your example, you would have a php file (example.php) that looks like this:

<?php
$custTrans = Customer.getTransactions();

$displ_transactions = array();

foreach ($custTrans as $ct){
     $transaction = array(
         'amount' => $ct[0],
         'date' => $ct[1];
         'product' => $ct[2];
     );
     $displ_transactions[] = $transaction; // this will push the transacion into the array
}
include 'example.tpl.php'
?>

And then you need a second file (example.tpl.php):

<?php foreach ($displ_transactions as $transaction) { ?>
     <div class="custTrans">
         <span class='custTransAmount'><?php echo $transaction['amount'] ?></span>;
         <span class='custTransDate'><?php echo $transaction['date'] ?></span>;
         <span class='custTransproduct'><?php echo $transaction['product'] ?></span>;
     </div>
<?php } ?>

Just call example.php in your browser and you will see the same result as you had before. This is all good and well for small websites, because this method causes some overhead. If you are serious about templating, use smarty. it's easy to learn, and it has automatic caching, so it's super fast.

I just realize you can also do it this way:

example.php:

<?php
$custTrans = Customer.getTransactions();

foreach ($custTrans as $ct){
     $amount = $ct[0];
     $date = $ct[1];
     $product = $ct[2];
     include 'example.tpl.php';
}
?>

example.tpl.php:

 <div class="custTrans">
     <span class='custTransAmount'><?php echo $amount ?></span>;
     <span class='custTransDate'><?php echo $date ?></span>;
     <span class='custTransproduct'><?php echo $product ?></span>;
 </div>

Use whatever suits you best :)

Comments