Search code examples
phpcodeigniterhmvc

How to load a controller from another controller in codeigniter?


I want to load a controller from a function in another controller because the library I integrated to my project I don't want to load it to the controller because I want to keep it clean and related.

I tried using modules but I still had to put controller in the url like

http://example.com/maincontroller/function
http://example.com/othercontroller/function

I have default controller so I can load http://example.com/function so how could I access the controller from a function from main so I don't have to put the controller in the url.

I'm still willing to use HMVC if I can load the controller function from the main controller function.


Solution

  • 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