2013年11月1日金曜日

CodeIgniterでGET, POSTの動作を分ける

FuelPHPで最初に便利だったのがhttpdのメソッドでコントローラーのアクションを分岐できるところ。
FuelPHPが動かないサーバの案件でCodeIgniterを使ったときに真っ先に追加したのがこの機能。

function action_xxx (){
function get_xxx (){
function post_xxx (){

と書くだけで、GET, POSTによるアクションの分岐が可能になります。


以下の内容のMy_Controller.phpを作成。

<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

class MY_Controller extends CI_Controller
{
var $uploaded;
var $view_headers;
var $view_footers;
public function __construct()
{
parent::__construct();
}
// action_, post_, get_への振り分け
public function _remap($method, $params = array())
{
if ($method == '') $method = 'index';
if (strtolower($this->input->server('REQUEST_METHOD')) == 'post')
{
// POST
if (method_exists($this, 'post_'.$method))
{
return call_user_func_array(array($this, 'post_'.$method), $params);
}
elseif (method_exists($this, 'action_'.$method))
{
return call_user_func_array(array($this, 'action_'.$method), $params);
}
else
{
show_404();
}
}
else
{
// GET
if (method_exists($this, 'get_'.$method))
{
return call_user_func_array(array($this, 'get_'.$method), $params);
}
elseif (method_exists($this, 'action_'.$method))
{
return call_user_func_array(array($this, 'action_'.$method), $params);
}
else
{
show_404();
}
}
}
public function view($viewfile, $data)
{
foreach ($this->view_headers AS $header_file)
{
$this->load->view($header_file, $data);
}
$this->load->view($viewfile, $data);
foreach ($this->view_footers AS $footer_file)
{
$this->load->view($footer_file, $data);
}
}
}

require_once dirname(__FILE__) . DIRECTORY_SEPARATOR . 'AUTH_Controller.php';
?>

0 件のコメント: