【发布时间】:2012-03-15 13:50:50
【问题描述】:
我正在学习 CakePHP,我的第一个 MVC,我有几个“最佳实践”问题。
这是我显示新闻文章的视图:
<h1><?php echo h($post['Post']['title'])?></h1>
<p><?php echo h($post['Post']['body'])?></p>
<?php foreach ($post['Comment'] as $comment): ?>
<div class="comment" style="margin-left:50px;">
<p><?php echo h($comment['body'])?></p>
</div>
<?php endforeach;
echo $this->element('newcomment', array("post_id" => $post['Post']['id']));?>
我认为您不能使用“添加”视图在另一个视图中添加评论,所以我创建了一个元素。我希望这是这个的最佳做法。
我的主要“问题”是:添加评论。 我是在表单中添加隐藏字段,还是将其添加到表单的操作中?
我选择了“id in action”部分,因为之后更容易重用它进行重定向。这是新的评论元素:
<h1>Add Comment</h1>
<?php
echo $this->Form->create('Comment',array('action' => 'add',
'url' => array($post_id)));
echo $this->Form->input('body', array('rows' => '3'));
echo $this->Form->end('Add comment');
?>
然后这是 CommentsController 中的“添加”功能:
public function add($post_id = null) {
if ($this->request->is('post')) {
$this->Comment->set(array('post_id'=>$post_id));
if ($this->Comment->save($this->request->data)) {
$this->Session->setFlash('Your comment has been added.');
//$this->redirect(array('action' => 'index'));
$this->redirect(array('controller' => 'posts', 'action' => 'view', $post_id));
} else {
$this->Session->setFlash('Unable to add your comment.');
}
}
}
应该是这样吗?
我希望可以在这里问这些问题。使用最佳实践对我来说非常重要。
【问题讨论】:
-
你的方法很好; @Dave 总结得很好,元素思想是创建可维护和可重用代码的好方法。请注意,用户可以轻松地在表单操作中操作
post_id值;允许他们对任何帖子发表评论,除非之前进行了适当的检查,或者使用了安全组件的表单输入哈希。 -
只有一件事:
$this->Comment->set(array('post_id'=>$post_id));应该是最后一行(对于这两种情况!) -
嘿,马克,怎么样?我认为在 save($this->request->data) 之前执行它会更合乎逻辑......之后我也不需要再执行一次 save() 吗?
标签: cakephp