Add a comment to an article in CakePHP

I am learning CakePHP, my first MVC, and I have a few "best practice" questions.

This is my view for showing a news article:

<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']));?> 

I did not think you could use the add view to add a comment to another view, so I created an element. I hope the best practice for this.

My main “problem” was this: adding a comment. Do I add a hidden field to the field or add it to the form action?

I went with the "id in action" part because it is easier to repeat it for redirection afterwards. This is the newcomment element:

 <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'); ?> 

And then this is the “add” function in the comment:

 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.'); } } } 

How should it be?

I hope it will be good to ask such questions here. Using best practices is very important to me.

+4
source share
1 answer

Considering your question as an overview of the concept, and not in turn, there are no problems with this general structure / method of its implementation.

Usually we have a "comments" element, which has everything there is - comments, a new block of comments ... etc. You can then pass in a variable if you do not want users to be able to comment on that particular thing or variable for the number of comments you want to show ... etc. This does not mean that it is better - it is simply better for us. Each site can present different scenarios that make it different in a better way.

I tried asking the “best practice” question for many things (including CakePHP), and what I found is usually no direct answer. If your code is simple, clean, well organized, and has data security / integrity issues, you're fine.

The only thing I would think about is good Ajax comments. Users become spoiled, and updating the page just to comment on something can be considered unpleasant.

Using a hidden field or URL is entirely up to you - as long as the data processing code is solid, it should not matter at all, and, again, it all comes down to preference.

+4
source

Source: https://habr.com/ru/post/1401607/


All Articles