今回は前回のログイン機能の実装
に引き続き、簡易ブログのログイン機能の実装を解説していきます。
尚、今回もCakePHP Cook bookのブログ作成チュートリアルに沿って作成を進めました。
こちらも是非一読お願いします。
投稿機能(一覧、追加、編集、削除)
サブタイトルにもある通り、上の4つの機能はコントローラー部分にまとめます。
今回はSubmitsController.phpとしますが、Cookbookで記述されているように
PostsController.phpが好ましいです。(テーブルの名前にもよります)
次はコントローラーの解説をしていきたいと思います。
SubmitsController.php
<?php
class SubmitsController extends AppController {
//どのヘルパとコンポーネントを使用するか
public $helpers = array('Html', 'Form', 'Flash');
public $components = array('Flash');
public function index() {
//投稿一覧表示
$this->set('submits', $this->Submit->find('all'));
}
public function view($id) {
//idからユーザー、投稿を見つける 見つからなければエラー表示
if (!$id) {
throw new NotFoundException(__('エラーです'));
}
$submit = $this->Submit->findById($id);
if (!$submit) {
throw new NotFoundException(__('エラーです'));
}
$this->set('submit', $submit);
}
public function add() {
//投稿機能 createでテーブル指定、saveメソッドでデータベースに保存
if ($this->request->is('post')) {
$this->Submit->create();
if ($this->Submit->save($this->request->data)) {
$this->Flash->success(__('投稿が完了しました'));
return $this->redirect(array('action' => 'index'));
}
$this->Flash->error(__('投稿に失敗しました'));
}
}
public function edit($id = null) {
//編集機能 viewと同じようにidから探し、見つからなければエラー表示
if (!$id) {
throw new NotFoundException(__('エラーです'));
}
$submit = $this->Submit->findById($id);
if (!$submit) {
throw new NotFoundException(__('エラーです'));
}
//編集機能requestで送られてきたidと編集内容をsaveで保存
//成功した場合一覧にリダイレクト、メッセージ表示
if ($this->request->is(array('submit', 'put'))) {
$this->Submit->id = $id;
if ($this->Submit->save($this->request->data)) {
$this->Flash->success(__('投稿編集が完了しました'));
return $this->redirect(array('action' => 'index'));
}
$this->Flash->error(__('投稿編集に失敗しました'));
}
if (!$this->request->data) {
$this->request->data = $submit;
}
}
public function delete($id) {
//削除機能get送信の場合エラーを投げかける(post送信時のみ削除可能)
if ($this->request->is('get')) {
throw new MethodNotAllowedException();
}
//post送信で送られてきたidから投稿を見つけ、削除処理
if ($this->Submit->delete($id)) {
$this->Flash->success(__('The submit with id: %s 削除が完了しました', h($id)));
} else {
$this->Flash->error(__('The submit with id: %s 削除に失敗しました', h($id)));
}
//削除に成功、失敗どちらの場合でも投稿一覧に移動し、メッセージ表示
return $this->redirect(array('action' => 'index'));
}
}
?>
コメントアウトした部分に処理の流れを記述しました。
以上がCakephpで作成した簡易ブログの投稿機能のコントローラー部分の解説になります!
是非参考になればと思います、お疲れ様でした。