How to load a controller from another controller in codeigniter? How to load a controller from another controller in codeigniter? codeigniter codeigniter

How to load a controller from another controller in codeigniter?


yes you can (for version 2)

load like this inside your controller

 $this->load->library('../controllers/whathever');

and call the following method:

$this->whathever->functioname();


You can't load a controller from a controller in CI - unless you use HMVC or something.

You should think about your architecture a bit. If you need to call a controller method from another controller, then you should probably abstract that code out to a helper or library and call it from both controllers.

UPDATE

After reading your question again, I realize that your end goal is not necessarily HMVC, but URI manipulation. Correct me if I'm wrong, but it seems like you're trying to accomplish URLs with the first section being the method name and leave out the controller name altogether.

If this is the case, you'd get a cleaner solution by getting creative with your routes.

For a really basic example, say you have two controllers, controller1 and controller2. Controller1 has a method method_1 - and controller2 has a method method_2.

You can set up routes like this:

$route['method_1'] = "controller1/method_1";$route['method_2'] = "controller2/method_2";

Then, you can call method 1 with a URL like http://site.com/method_1 and method 2 with http://site.com/method_2.

Albeit, this is a hard-coded, very basic, example - but it could get you to where you need to be if all you need to do is remove the controller from the URL.


You could also go with remapping your controllers.

From the docs: "If your controller contains a function named _remap(), it will always get called regardless of what your URI contains.":

public function _remap($method){    if ($method == 'some_method')    {        $this->$method();    }    else    {        $this->default_method();    }}


you cannot call a controller method from another controller directly

my solution is to use inheritances and extend your controller from the library controller

class Controller1 extends CI_Controller {    public function index() {        // some codes here    }    public function methodA(){        // code here    }}

in your controller we call it Mycontoller it will extends Controller1

include_once (dirname(__FILE__) . "/controller1.php");class Mycontroller extends Controller1 {    public function __construct() {        parent::__construct();    }    public function methodB(){        // codes....    }}

and you can call methodA from mycontroller

http://example.com/mycontroller/methodA

http://example.com/mycontroller/methodB

this solution worked for me