我在學習CakePHP,我的第一個MVC,我有一些「最佳實踐」的問題。在CakePHP的文章中添加評論
這是我用來顯示新聞文章的觀點:
<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」部分一起使用,因爲之後重用它很容易。這是newcomment元素:
<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'值;允許他們對*任何*帖子發表評論,除非在之前進行了適當的檢查,或者使用了安全組件的表單輸入散列。 – Ross 2012-03-15 14:08:07
只有一兩件事:'$這個 - > Comment->設置(陣列( 'POST_ID'=> $ POST_ID));'應該是最後一行(!對於這兩種情況下) – mark 2012-03-15 14:40:29
嘿馬克,怎麼會這樣?我認爲這將是更符合邏輯的節省($這個 - >請求 - >數據)之前,做...難道我必須做的另一個保存()之後,過? – John 2012-03-16 12:37:13