使用面向对象的 PHP,应该在哪里呈现 HTML?
业务流程包括维护客户记录的多项操作。
每个业务流程的渲染是否应该得到一个单独的 PHP 文件? IE。 viewCustomerTransactions.php?
这样的代码应该放在哪里?
$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>';
}
也许像 codeigniter 这样的 MVC 框架会更好?
最佳答案
我仍在寻找最好的方法来保持 php 和布局的分离,同时又不会产生太多的困惑。目前我非常喜欢包含模板方法,因为它非常简单而且没有任何限制。
因此,对于您的示例,您将有一个如下所示的 php 文件 (example.php):
<?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'
?>
然后你需要第二个文件(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 } ?>
只需在浏览器中调用 example.php,您就会看到与之前相同的结果。 这对小型网站来说很好,因为这种方法会产生一些开销。如果您认真对待模板,请使用 smarty。它简单易学,并且具有自动缓存,因此非常快。
我刚刚意识到你也可以这样做:
例子.php:
<?php
$custTrans = Customer.getTransactions();
foreach ($custTrans as $ct){
$amount = $ct[0];
$date = $ct[1];
$product = $ct[2];
include 'example.tpl.php';
}
?>
例子.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>
使用最适合你的:)
关于php - 在面向对象的 PHP 设计中,HTML 应该在哪里呈现?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4726877/