How to set default function in codeIgniter when I

2019-04-10 16:35发布

问题:

The controller like this:

class Abc extends CI_controller{
  public function index(){...}

  public function f1(){...} 
}

If url is http://host/app/Abc/index it get function index
If url is http://host/app/Abc/f1 it get function f1
If url is http://host/app/Abc it get function index because it is default
But if url is http://host/app/Abc/f2 it print 404 not found

I expected that if url is http://host/app/Abc/f2 it can turn to index function.
If can't do this,I want to add new function automatically,What should I do?

EDIT
I want to use it in just a specific class, can I edit global routing? How?

回答1:

Two ways you can do it first edit routes.php file and change 404_override to controller function this will redirect all your 404 request to that controller function

form
$route['404_override'] = 'welcome';

to
$route['404_override'] = 'ABC/index';

second option is within controller you can use _remap method/function to check either function/method exist or not. controller will be like this

class Abc extends CI_controller{

  function _remap($method_name = 'index'){

             if(!method_exists($this, $method_name)){
                $this->index();
             }
             else{
                $this->{$method_name}();
             }
         }

  public function index(){...}

  public function f1(){...} 
}


回答2:

Same, but using arguments. If not, arguments will fail to pass, pagination, filtering, parameters will not work.


class Abc extends CI_controller{

    function _remap($method_name = '',$args){
                if(!method_exists($this, $method_name)){
                    //$this->index($args);
                    call_user_func_array  (array($this,'index'), $args);
                 }
                 else{
                    //$this->{$method_name}();
                    call_user_func_array  (array($this,$method_name),  $args);
                 }

             }
    public function index($a,$b,$c){...}

    public function f1($a,$b){...} 

}


回答3:

Let me do some notes here and make a collection in my favorite,Thanks all very much!

class Abc extends CI_controller{

  function _remap($method_name = 'index'){

             if(!method_exists($this, $method_name)){
                $this->index($method_name);
             }
             else{
                $this->{$method_name}($method_name);
             }
         }

  public function index($method_name='index'){...}

}

effectively,I just want this _remap function because the methods I request are all non-existed.
This is good! Yes! I suddenly see the light!