Codeigniter : calling a method of one controller from other

koool picture koool · Jun 28, 2011 · Viewed 107.4k times · Source

I have two controllers a and b.

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

Could anyone help explain how I can achieve this?

Answer

Aren picture Aren · Jun 28, 2011

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);