Please wait for 15 seconds...

Monday 14 January 2013



Today I will show you how to load a controller within another controller. Initially I was thinking that it will be very complex but thanks for Codeigniter. So lets start it.

First we have to extend the CI_Loader class. So create a file called MY_Loader in applications/core folder. If you have made changes in config.php $config['subclass_prefix'] rather than "MY_" then you should make these changes here also. Suppose you have set


$config['subclass_prefix'] = 'CORE_'

Then your core loader file will be CORE_Loader rather than MY_Loader.

Now put the following code in your MY_Loader file.

<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
class MY_Loader extends CI_Loader{
    public function __construct(){
     
    }
    public function controller($file_name){
        $CI = & get_instance();
     
        $file_path = APPPATH.'controllers/'.$file_name.'.php';
        $object_name = $file_name;
        $class_name = ucfirst($file_name);
     
        if(file_exists($file_path)){
            require $file_path;
         
            $CI->$object_name = new $class_name();
        }
        else{
            show_error("Unable to load the requested controller class: ".$class_name);
        }
    }
}

Now we can access a controller within any other controller.

Home (Parent Controller):


<?php
class Home extends CI_Controller{
    function __construct(){
        parent::__construct();
     
        $this->load->controller('child_controller');
    }
    public function index(){
        $this->child_controller->index();
    }
}
?>

Child Controller:


<?php
class Child_controller extends CI_Controller {
    function __construct(){
        parent::__construct();
    }
    public function index(){
        echo "<p>Welcome to child controller<p>";
    }
}
?>

If you have any question/suggestion feel free to post a comment below.

UPDATE
Always load custom controller at the bottom of __construct() method else it can cause problem. e.g.
 function __construct(){
      parent::__construct();
   
      /* bottom */
      $this->load->controller('child_controller');
}

And thanks to anonymous(as posted his/her name in comment) to point it out.

UPDATE(25th September, 2016)
Previously I was calling parent constructor of CI_Loader class in MY_Loader class and it was causing many problems. Please use blank constructor instead, it is required. e.g.
 class MY_Loader extends CI_Loader{
    public function __construct(){
     
    }
}

Posted by Atul

71 comments:

  1. Thanks a lot. It save me in an urgent moment.

    ReplyDelete
    Replies
    1. Thank you, I am glad that you it helped you.

      Delete
  2. Thanks for this. Just what I was looking for.

    ReplyDelete
  3. I tried this and it seemed to work. However, if I load a model after I've loaded a controller, the model does not load. I get an error when I try to access one of the methods of the model.
    If I load the controller last, then it all works.
    Any ideas?

    ReplyDelete
    Replies
    1. Can you tell me, what error message it is showing?

      Delete
  4. am also havin the same problem when i load a model...The error is that it cant load the methods in the model....eg Fatal error: Call to a member function get_news() on a non-object in D:\xampp\htdocs\code\application\controllers\news.php on line 27

    ReplyDelete
    Replies
    1. This method is not to load controller within a model. You can load a controller within another controller using this method.

      Delete
  5. Great One!!! Just the way I wanted it!!

    ReplyDelete
  6. Great One,Thanks Alot!! Saved me a lot of time!!!

    ReplyDelete
  7. Good technical solutins is given in this blog. However, I want to know about advance nesting controoller techniques.

    ReplyDelete
  8. Hi I tried the code, copied the same thing but got a error :Fatal error: Class 'MY_Controller' not found in /var/www/mycodelgniter/application/controllers/Test_controller_1.php on line 2. would you please help me

    ReplyDelete
  9. Can you make it load multiple sub directories ie controller / folder / folder / controller.php

    ReplyDelete
    Replies
    1. Yes, I just updated the tutorial. Download new version here.
      http://demo.techsirius.com/index.php?p=check_fblike&download_file=techsirius.com_load_controller_within_another_controller_in_CI_V1.01_739280.zip

      Delete
    2. Can not download even though liked. Can you make sure it when add controllers it also can add more than one folder at the moment can not ad folder i.e $this->load->controller('folder/folder/file); and does not work when ad more then one array() in index

      Delete
  10. Is there away to get it to load like $data['name'] = $this->load->controller('file);

    ReplyDelete
  11. Thanks for Knowledge sharing....It really helped me alot

    ReplyDelete
    Replies
    1. Your welcome Nitin. You can also ask me tutorial request on this page.
      http://www.techsirius.com/p/request-message.html

      Delete
  12. I did it same you but my page empty

    ReplyDelete
    Replies
    1. Download the script and give it a try.
      http://demo.techsirius.com/index.php?p=check_fblike&download_file=techsirius.com_load_controller_within_another_controller_in_CI_V1.01_739280.zip

      Delete
  13. Esta muy bien pero me funciona para cargar un solo controlador, cuando quiero cargar el segundo controlador, lo desconoce.
    Lo cargo en el contructor asi:
    $this->load->controller('area');
    $this->load->controller('cargo');

    y accedo en el index como:
    $listado_areas_sede_cbo = $this->area->obtener_listado_areas_sede_cbo();
    $listado_cargos_cbo = $this->cargo->obtener_listado_cargos_cbo();

    y me muestra el siguiente error:
    A PHP Error was encountered

    Severity: Notice

    Message: Undefined property: Personal::$cargo

    Filename: controllers/personal.php

    Line Number: 41

    Puedes indicarme como cargo 2 controladores, por favor.

    ReplyDelete
    Replies
    1. Sí, esta versión sólo funciona para un controlador. Estoy tratando de encontrar un trabajo en torno a varios controladores. Como lo consigo voy a publicar aquí, gracias por señalar esto y perdóname por cualquier palabra española pobre si he usado.

      Delete
  14. When load more than one controller into parent::__construct(); and also on index page does not work on works with one controller only. I need to make multiple arrays $data['header] $this->header->index(); up to 6 more but only works with one. And does not detect sub folders the loader.

    ReplyDelete
  15. Hi Atul, I got this error when trying to load the other controller
    Fatal error: Call to undefined method CI_Loader::controller() in C:\xampp\htdocs\login_crud\application\controllers\home.php on line 6

    load->controller('person'); //trying to load the \controllers\person.php
    }

    ReplyDelete
    Replies
    1. Have you created MY_Loader class in "application/core" directory? I suggest you to download tutorial file and compare with your codes. If you still have any problem feel free to send me your code at techsirius@live.com. I will try to fix it.

      Delete
  16. I'm do not allow to download the code...

    ReplyDelete
  17. Gihan Wijethunga

    I have got this error
    Fatal error: Call to undefined method CI_Loader::controller() in C:\xampp\htdocs\finance\application\controllers\home.php on line 8

    ReplyDelete
  18. If you can please help me to fix this error, I have already send you a email also,I'm in a critical situation

    ReplyDelete
    Replies
    1. I have sent you some solution. Please check in your email Google Plus message box.

      Delete
  19. thanx very much for your help!!!

    ReplyDelete
  20. email- gihansalith3@gmail.com

    ReplyDelete
  21. using Codeigniter I need to submit form data using ajax and get auto increment id of that particular inserted record and display it on div in the view,please help me I'm in a critical situation.

    ReplyDelete
    Replies
    1. Use following code

      $this->db->insert($table, $db_data);
      $row_id = mysql_insert_id();

      Delete
  22. I have send you a question

    ReplyDelete
    Replies
    1. Check in your inbox. I have sent you back solved project.

      Delete
  23. Hi, I did like this but it fails...
    load->controller('child_controller');
    }
    public function index(){
    //echo "parent controller";die;
    $this->child_controller->index();
    }
    }
    //After this i try this...
    <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

    class Child_controller extends CI_Controller {
    function __construct(){
    parent::__construct();
    }
    public function index(){
    echo "Welcome to child controller"die;;
    }
    }
    //it gives this...
    Fatal error: Call to undefined method CI_Loader::controller() in C:\xampp\htdocs\default_ci\application\controllers\parent_controller.php on line 7
    ...???

    ReplyDelete
    Replies
    1. Have you created MY_Loader class in application/core?

      Delete
    2. Must the filename be "MY_Loader.php" instead of "MY_Loader"?
      I had the same error and it worked for me by adding .php.
      By the way, thanks a lot!

      Delete
  24. Great job...it works.........Thanks yaar...

    ReplyDelete
  25. hi Atul,
    I have send you a email,please kindly check it and give me a solution. I'm in a critical situation

    ReplyDelete
  26. Hello Athul, I ahve send you a question...

    ReplyDelete
  27. I have send you a question

    ReplyDelete
  28. how about more than 2 controllers? controller1, controller2, controller3 ....

    ReplyDelete
  29. Hi Atul,

    This method has few issues,

    1. We cannot load more than one controller, also we cannot load any library after loading controller these way, it throws error.

    2. When using with form_validation library the form validation helper functions are overrided, which mean loading controller after form validation in view form validation function return nothing.

    ReplyDelete
    Replies
    1. Well following this tutorial, you can autoload only one controller and load this controller at the bottom of the constructor function else it will give you headache.

      I am working on a method by which it would be possible to load more than one controller.

      Subscribe techsirius for further updates.

      Delete
  30. Hello,

    I try your code, it works, but if I add a session var in the child controller, I have an error :


    The child controller :

    session->set_userdata('message','Authentification réussie');

    }
    }

    The error :

    Fatal error: Call to a member function set_userdata() on a non-object in C:\wamp\www\test\application\controllers\child_controller.php on line 11

    ReplyDelete
  31. Hello,

    I have a problem with your method.

    If I add for example this instruction in the child_controler, it does't work

    public function index(){
    echo 'Welcome to child controller";
    $this->session->set_userdata('message','One message');
    }

    Error message

    Severity: Notice

    Message: Undefined property: Child_controller::$session



    ReplyDelete
  32. Unable to locate the specified class: Cache.php error on my page plz help

    ReplyDelete
  33. Can you please show me some screen shorts, so I can explain more precise..

    ReplyDelete
  34. Unable to locate the specified class: Session.php

    ReplyDelete
    Replies
    1. Can you show me error message and code snippet??

      Delete
    2. Hi Atul, this error is only in CI 3.0, in version 2.2 works perfect. ¿Do you have a solutions?

      Delete
    3. Are you using CI 3.0? I have the same problem. Do you know how to fix it?

      Delete
    4. I did some update in this hack. Please find updates above and let me know any problem. I have also tested it in codeigniter version 3.1.0

      Delete
  35. (Unable to locate the specified class: Session.php) showing this

    ReplyDelete
  36. Fatal error: Cannot redeclare class
    $this->load->controller("api");
    when i use this method . got this error



    Fatal error: Cannot redeclare class baseController in D:\wamp\www\project\application\controllers\baseController.php on line 1437

    ReplyDelete
  37. Muchas gracias, funciona

    ReplyDelete
  38. Me sale este error:

    Unable to locate the specified class: Session.php

    ReplyDelete
    Replies
    1. Corregido el error, por favor, comprueba por encima de la última actualización

      Delete
  39. Message: Call to undefined method CI_Loader::controller() please help me.

    ReplyDelete
    Replies
    1. Please check if you have placed MY_Loader.php file in application core directory, which contains controller method.

      Delete
  40. Hi Atul, I copy paste the code then run it, but error pop up. Unable to load the requested controller class: Child_controller. Please help.

    ReplyDelete
  41. Hi , I did like this but i got a error message as like this

    "Unable to locate the specified class: Session.php"

    ReplyDelete
    Replies
    1. Please tell me the CI version you are using

      Delete
  42. I have this error with Codeigniter 3.0.6:
    "
    A PHP Error was encountered

    Severity: Notice

    Message: Only variable references should be returned by reference

    Filename: core/Common.php

    Line Number: 257
    "

    Thanks

    ReplyDelete
  43. Hello again, I solved the other error, but I have a problem with session from home to child controller, exactly:

    A PHP Error was encountered

    Severity: Notice

    Message: Undefined property: Perfil_controller::$session

    Filename: controllers/perfil_controller.php

    Line Number: 15

    ReplyDelete
  44. thnk you very much.....
    its really helpfull....

    ReplyDelete

Techsirius on Facebook