Sunday, October 25, 2015

Codeigniter - The best practice in _remap() function

Instead of using like this:

function _remap($method)
{
         $array = array('method1','method2','method3','method4','method5','method6','method7',...);
         in_array($method, $array) ? $this->method() : $this->index()
}


to


function _remap($method)
    {
        $arr_raw_method_registered = get_class_methods(__CLASS__);
        $arr_remove_element = array('get_instance');
        $arr_method_registered = array_filter($arr_raw_method_registered, function($item)use($arr_remove_element) 
        {
            if (in_array($item, $arr_remove_element) || $item[0] == '_'):
                return false; 
            else:
                return true;
            endif;
        });
        
        in_array($method, $arr_method_registered) ? $this->$method() : $this->index();
    }

The function covers all defined function on that class.



No comments:

Post a Comment