I have a home
controller with an index
action that displays a set of featured products. However, the products are managed through a product
Just to add more information to what Zain Abbas said:
Load the controller that way, and use it like he said:
$this->load->library('../controllers/instructor');
$this->instructor->functioname();
Or you can create an object and use it this way:
$this->load->library('../controllers/your_controller');
$obj = new $this->your_controller();
$obj->your_function();
Hope this can help.
Based on @Joaquin Astelarra response, I have managed to write this little helper named load_controller_helper.php:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
if (!function_exists('load_controller'))
{
function load_controller($controller, $method = 'index')
{
require_once(FCPATH . APPPATH . 'controllers/' . $controller . '.php');
$controller = new $controller();
return $controller->$method();
}
}
You can use/call it like this:
$this->load->helper('load_controller');
load_controller('homepage', 'not_found');
Note: The second argument is not mandatory, as it will run the method named index, like CodeIgniter would.
Now you will be able to load a controller inside another controller without using HMVC.
Later Edit: Be aware that this method might have unexpected results. Always test it!
Just use
..............
self::index();
..............
Load it like this
$this->load->library('../controllers/instructor');
and call the following method:
$this->instructor->functioname()
This works for CodeIgniter 2.x.
There are plenty of good answers given here for loading controllers within controllers, but for me, this contradicts the mvc pattern.
The sentence that worries me is;
(filled with data processed by the product controller)
The models are there for processing and returning data. If you put this logic into your product model then you can call it from any controller you like without having to try to pervert the framework.
Once of the most helpful quotes I read was that the controller was like the 'traffic cop', there to route requests and responses between models and views.
In this cases you can try some old school php.
// insert at the beggining of home.php controller
require_once(dirname(__FILE__)."/product.php"); // the controller route.
Then, you'll have something like:
Class Home extends CI_Controller
{
public function __construct()
{
parent::__construct();
$this->product = new Product();
...
}
...
// usage example
public function addProduct($data)
{
$this->product->add($data);
}
}
And then just use the controller's methods as you like.