How to set default function in codeIgniter when I visit Class with non-existent route?

淺唱寂寞╮ 提交于 2020-01-01 14:49:32

问题


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!



来源:https://stackoverflow.com/questions/25176713/how-to-set-default-function-in-codeigniter-when-i-visit-class-with-non-existent

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!