ぶろぐ

日記です

postとgetでメソッドを振り分けたい


こんなの書いてた。if文でpostであるかどうかのの判断をしている。

<?php
public function action_del()
{
	// POST以外は処理しない
	if(Input::method() != 'POST') {
		Session::set_flash('error','POSTでアクセスしてちょ');
		Response::redirect('example/index');
	}

	// 削除処理
	$id = Input::post('id', null);
	$hoge = Model_Hoge::find($id);
	$hoge->delete();

	Session::set_flash('success','投稿を削除しました');

	Response::redirect('example/index');
}

でもなんかこれ、おれがやることじゃない。フレームワークがやることだ、とか思ってググって見たらやっぱりあった。

<?php
/** postならdelete処理 */
public function post_del()
{
	// 削除処理
	$id = Input::post('id', null);
	$hoge = Model_Hoge::find($id);
	$hoge->delete();

	Session::set_flash('success','投稿を削除しました');

	Response::redirect('example/index');
}

/** getならdeleteするページに飛ばす */
public function get_del()
{
	$this->template->title = '削除';
	$this->template->content = View::forge('example/del');
}

こっちのほうが本質でないコードを書かなくて済むので良い感じ。