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
Then your core loader file will be CORE_Loader rather than MY_Loader.
Now put the following code in your MY_Loader file.
Now we can access a controller within any other controller.
If you have any question/suggestion feel free to post a comment below.
UPDATE
And thanks to anonymous(as posted his/her name in comment) to point it out.
UPDATE(25th September, 2016)
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);
}
}
}
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();
}
}
?>
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>";
}
}
?>
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');
}
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(){
}
}
public function __construct(){
}
}
Thanks a lot. It save me in an urgent moment.
ReplyDeleteThank you, I am glad that you it helped you.
DeleteThanks for this. Just what I was looking for.
ReplyDeleteI 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.
ReplyDeleteIf I load the controller last, then it all works.
Any ideas?
Can you tell me, what error message it is showing?
Deleteam 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
ReplyDeleteThis method is not to load controller within a model. You can load a controller within another controller using this method.
DeleteGreat One!!! Just the way I wanted it!!
ReplyDeleteGreat One,Thanks Alot!! Saved me a lot of time!!!
ReplyDeleteGood technical solutins is given in this blog. However, I want to know about advance nesting controoller techniques.
ReplyDeleteHi 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
ReplyDeleteYes why not. Send me your code.
DeleteCan you make it load multiple sub directories ie controller / folder / folder / controller.php
ReplyDeleteYes, I just updated the tutorial. Download new version here.
Deletehttp://demo.techsirius.com/index.php?p=check_fblike&download_file=techsirius.com_load_controller_within_another_controller_in_CI_V1.01_739280.zip
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
DeleteIs there away to get it to load like $data['name'] = $this->load->controller('file);
ReplyDeleteThanks for Knowledge sharing....It really helped me alot
ReplyDeleteYour welcome Nitin. You can also ask me tutorial request on this page.
Deletehttp://www.techsirius.com/p/request-message.html
I did it same you but my page empty
ReplyDeleteDownload the script and give it a try.
Deletehttp://demo.techsirius.com/index.php?p=check_fblike&download_file=techsirius.com_load_controller_within_another_controller_in_CI_V1.01_739280.zip
Esta muy bien pero me funciona para cargar un solo controlador, cuando quiero cargar el segundo controlador, lo desconoce.
ReplyDeleteLo 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.
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.
DeleteWhen 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.
ReplyDeleteHi Atul, I got this error when trying to load the other controller
ReplyDeleteFatal 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
}
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.
DeleteI'm do not allow to download the code...
ReplyDeleteGihan Wijethunga
ReplyDeleteI 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
If you can please help me to fix this error, I have already send you a email also,I'm in a critical situation
ReplyDeleteI have sent you some solution. Please check in your email Google Plus message box.
Deletethanx very much for your help!!!
ReplyDeleteemail- gihansalith3@gmail.com
ReplyDeleteusing 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.
ReplyDeleteUse following code
Delete$this->db->insert($table, $db_data);
$row_id = mysql_insert_id();
I have send you a question
ReplyDeleteCheck in your inbox. I have sent you back solved project.
DeleteHi, I did like this but it fails...
ReplyDeleteload->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
...???
Have you created MY_Loader class in application/core?
DeleteMust the filename be "MY_Loader.php" instead of "MY_Loader"?
DeleteI had the same error and it worked for me by adding .php.
By the way, thanks a lot!
Great job...it works.........Thanks yaar...
ReplyDeletehi Atul,
ReplyDeleteI have send you a email,please kindly check it and give me a solution. I'm in a critical situation
Hello Athul, I ahve send you a question...
ReplyDeleteI have send you a question
ReplyDeletehow about more than 2 controllers? controller1, controller2, controller3 ....
ReplyDeleteCI do not allow.
DeleteGreat job.. Thank you..
ReplyDeleteGreat Job..Thank you..
ReplyDeleteHi Atul,
ReplyDeleteThis 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.
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.
DeleteI am working on a method by which it would be possible to load more than one controller.
Subscribe techsirius for further updates.
Hello,
ReplyDeleteI 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
Hello,
ReplyDeleteI 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
Unable to locate the specified class: Cache.php error on my page plz help
ReplyDeleteCan you please show me some screen shorts, so I can explain more precise..
ReplyDeleteUnable to locate the specified class: Session.php
ReplyDeleteCan you show me error message and code snippet??
DeleteHi Atul, this error is only in CI 3.0, in version 2.2 works perfect. ¿Do you have a solutions?
DeleteAre you using CI 3.0? I have the same problem. Do you know how to fix it?
DeleteI 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(Unable to locate the specified class: Session.php) showing this
ReplyDeleteFatal error: Cannot redeclare class
ReplyDelete$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
Muchas gracias, funciona
ReplyDeleteMe sale este error:
ReplyDeleteUnable to locate the specified class: Session.php
Corregido el error, por favor, comprueba por encima de la última actualización
Deletewhat's that?
ReplyDeleteMessage: Call to undefined method CI_Loader::controller() please help me.
ReplyDeletePlease check if you have placed MY_Loader.php file in application core directory, which contains controller method.
DeleteHi Atul, I copy paste the code then run it, but error pop up. Unable to load the requested controller class: Child_controller. Please help.
ReplyDeleteHi , I did like this but i got a error message as like this
ReplyDelete"Unable to locate the specified class: Session.php"
Please tell me the CI version you are using
DeleteI have this error with Codeigniter 3.0.6:
ReplyDelete"
A PHP Error was encountered
Severity: Notice
Message: Only variable references should be returned by reference
Filename: core/Common.php
Line Number: 257
"
Thanks
Hello again, I solved the other error, but I have a problem with session from home to child controller, exactly:
ReplyDeleteA PHP Error was encountered
Severity: Notice
Message: Undefined property: Perfil_controller::$session
Filename: controllers/perfil_controller.php
Line Number: 15
thnk you very much.....
ReplyDeleteits really helpfull....