Welcome to Abdul Malik Ikhsan's Blog

getParam CodeIgniter helper

Posted in Tutorial PHP by samsonasik on March 14, 2009

Kalau di zend Framework, kita bisa gunakan $this->getParam untuk memanggil suatu parameter setelah nama parameter tersebut, misal http://localhost/namaKelasKontroller/namaMethod/namasegment/isisegment/namasegment2/isisegment2 dan seterusnya, tinggal tulis $this->getParam(namasegment), kalau di CI, kita harus hafal dia berada pada segment ke berapa, halah gubrak ( atau saya yang belum nemu aja ya, he..he..).
Nah, untuk mengatasinya, kita bisa mengantisipasi dengan membuat sebuah helper baru, misal use_param_helper , di simpan dalam ./system/application/helpers/use_param_helper.php , berikut code programnya,

<?php
    if ( ! function_exists('getParam'))
    {
        function  getParam($param)
        {
            $ci = & get_instance();
            $totalsegment = $ci->uri->total_segments();
            $resultparam = "";
            for($i=1;$i<=$totalsegment;$i++) {
                if ($ci->uri->segment($i)==$param) {
                    $resultparam = $ci->uri->segment($i+1);
                    break;
                }
            }
            return $resultparam;
        }
    }
/* End of file use_param_helper.php */
/* Location: ./system/application/helpers/use_param_helper.php */

kita autoload aja supaya mudah, di ./system/application/config/autoload.php kita bisa atur di code program :

//...
$autoload['helper'] = array('url', 'use_param');
//...

Sekarang kita coba di controller, di sini saya coba di controller TestParam :

id/1/nama/andi
Yup, asik kan, jadi ga perlu lagi ngitung segment ke berapanya …

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: