첫 번째 MVC 인 CakePHP를 배우고 있으며 몇 가지 "모범 사례"에 대한 질문이 있습니다.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
오직 한가지 : $ this-> Comment-> set (array ('post_id'=> $ post_id));는 마지막 줄이어야합니다 (두 경우 모두!) – mark
안녕하세요. 나는 save ($ this-> request-> data) 전에 그것을하는 것이 더 논리적 일 것이라고 생각했다 ... 나는 나중에 또 다른 save()를 할 필요가 없을까? – John