Codeigniter : calling a method of one controller from other

后端 未结 10 1929
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-05 01:48

I have two controllers a and b.

I would like to call a method of controller a from a method of controller b.

相关标签:
10条回答
  • 2020-12-05 02:36

    Controller to be extended

    require_once(PHYSICAL_BASE_URL . 'system/application/controllers/abc.php');
    
            $report= new onlineAssessmentReport();
            echo ($report->detailView());
    
    0 讨论(0)
  • 2020-12-05 02:39

    You can use the redirect URL to controller:

    Class Ctrlr1 extends CI_Controller{
    public void my_fct1(){
    redirect('Ctrlr2 /my_fct2', 'refresh');
    }
    }
    
    
    Class Ctrlr2 extends CI_Controller{
    public void my_fct2(){
    $this->load->view('view1');
    }
    }
    
    0 讨论(0)
  • 2020-12-05 02:41

    I posted a somewhat similar question a while back, but regarding a model on CI.

    Returning two separate query results within a model function

    Although your question is not exactly the same, I believe the solution follows the same principle: if you're proposing to do what you mention in your question, there may be something wrong in the way you're coding and some refactoring could be in order.

    The take home message is that what you're asking is not the way to go when working with MVC.

    The best practice is to either use a Model to place reusable functions and call them in a controller that outputs the data through a view -- or even better use helpers or libraries (for functions that may be needed repeatedly).

    0 讨论(0)
  • 2020-12-05 02:42

    This is not supported behavior of the MVC System. If you want to execute an action of another controller you just redirect the user to the page you want (i.e. the controller function that consumes the url).

    If you want common functionality, you should build a library to be used in the two different controllers.

    I can only assume you want to build up your site a bit modular. (I.e. re-use the output of one controller method in other controller methods.) There's some plugins / extensions for CI that help you build like that. However, the simplest way is to use a library to build up common "controls" (i.e. load the model, render the view into a string). Then you can return that string and pass it along to the other controller's view.

    You can load into a string by adding true at the end of the view call:

    $string_view = $this->load->view('someview', array('data'=>'stuff'), true);
    
    0 讨论(0)
提交回复
热议问题