博客开发中关于删除帖子的知识,接下来,让我们做一个方式让用户删除帖子。首先删除PostsController()行动:
public function delete($id) {
if ($this->request->is('get')) {
throw new MethodNotAllowedException();
}
if ($this->Post->delete($id)) {
$this->Session->setFlash(
__('The post with id: %s has been deleted.', h($id))
);
return $this->redirect(array('action' => 'index'));
}
}
这个逻辑删除指定的帖子$ id,并使用$ This - >会话- > setFlash()来显示用户确认消息后重定向到/职位。如果用户试图做一个使用GET请求删除,我们抛出一个异常。未捕获的异常捕获CakePHP的异常处理程序,并显示一个错误页面。有很多内置的异常,可以用来表示各种应用程序可能需要生成HTTP错误。
因为我们只是执行一些逻辑和重定向,这个动作没有观点。您可能需要更新您的索引视图允许用户删除帖子的链接,但是:
<!-- File: /app/View/Posts/index.ctp -->
<h1>Blog posts</h1>
<p><?php echo $this->Html->link('Add Post', array('action' => 'add')); ?></p>
<table>
<tr>
<th>Id</th>
<th>Title</th>
<th>Actions</th>
<th>Created</th>
</tr>
<!-- Here's where we loop through our $posts array, printing out post info -->
<?php foreach ($posts as $post): ?>
<tr>
<td><?php echo $post['Post']['id']; ?></td>
<td>
<?php
echo $this->Html->link(
$post['Post']['title'],
array('action' => 'view', $post['Post']['id'])
);
?>
</td>
<td>
<?php
echo $this->Form->postLink(
'Delete',
array('action' => 'delete', $post['Post']['id']),
array('confirm' => 'Are you sure?')
);
?>
<?php
echo $this->Html->link(
'Edit', array('action' => 'edit', $post['Post']['id'])
);
?>
</td>
<td>
<?php echo $post['Post']['created']; ?>
</td>
</tr>
<?php endforeach; ?>
</table>
使用postLink()将创建一个链接,使用JavaScript来做一个POST请求删除帖子。允许使用GET请求的内容要删除是危险的,作为web爬虫程序可以不小心删除所有内容。