CodeIgniterの_remapメソッドでパラメータを指定する方法
デフォルトのCodeIgniterでの _remap() メソッドでは、メソッド名の指定のみ有効で、パラメータ付きのコントローラのメソッドを再マッピングできませんでした。
調べたところ、Codeigniter.php のクラス内で再マッピングしている場所はこちら
if (method_exists($CI, '_remap')) { $CI->_remap($method); } else { // is_callable() returns TRUE on some versions of PHP 5 for private and protected // methods, so we'll use this workaround for consistent behavior if ( ! in_array(strtolower($method), array_map('strtolower', get_class_methods($CI)))) { show_404("{$class}/{$method}"); } // Call the requested method. // Any URI segments present (besides the class/function) will be passed to the method for convenience call_user_func_array(array(&$CI, $method), array_slice($URI->rsegments, 2)); }
再マッピングしない場合は、call_user_func_arrayをつかってパラメータを配列で渡していますが、
_remapを使った場合、メソッドしか指定していません。
なので、これを使えるようにカスタマイズしてみました。
if (method_exists($CI, '_remap')) { $CI->_remap($method, array_slice($URI->rsegments, 2)); } else { // is_callable() returns TRUE on some versions of PHP 5 for private and protected // methods, so we'll use this workaround for consistent behavior if ( ! in_array(strtolower($method), array_map('strtolower', get_class_methods($CI)))) { show_404("{$class}/{$method}"); } // Call the requested method. // Any URI segments present (besides the class/function) will be passed to the method for convenience call_user_func_array(array(&$CI, $method), array_slice($URI->rsegments, 2)); }
これだけではだめで、
コントローラで_remap()を使う場合に
function _remap($method, $params = array())
とします。
で、条件によって振り分ける際に、
$paramsに値がある場合は
call_user_func_array(array($this, $method), $params);
無い場合は
$this->$method();
とすることで、パラメータ付きのものが渡せるようになりました。
これ、本家にパッチを贈ろうかと思いますが、、なぜ_remapの場合methodのみにしてるんでしょうかね?
理由があるのかもしれませんが。。。
[PHP][CodeIgniter]CodeIgniterのanchor()関数でimgタグを使う
CIでanchor()タグの第二引数に <img タグを入れると、おかしな <a タグが生成されます。
これは、自動的に title に第二引数が渡されるためです。
<img タグを入れて画像のリンクを生成する場合は
anchor('hogehoge/fugafuga', '<img src="hoge" />', array('title'=>'ほげげ'));
として、第三引数にタイトルを入れればOKです。
ちょっとした方法ですね。