Reputation: 14862
I have a custom module, and now want to call the add()
function from checkout/cart
. How do I call the controller and function?
I have tried $this->load->controller('checkout/cart');
but this returns a fatal exception.
I am using OpenCart v 1.5.6.4
Upvotes: 1
Views: 4719
Reputation: 22941
The problem with getChild()
is it only works if the controller calls $this->response->setOutput()
or echo
at the end - producing actual output. If on the other hand, you want to call a controller method that returns a variable response, it isn't going to work. There is also no way to pass more than one argument since getChild()
accepts only one argument to pass, $args
.
My solution was to add this bit in 1.5.6.4 to system/engine/loader.php which allows you to load a controller and call it's methods in the same way as you would a model:
public function controller($controller) {
$file = DIR_APPLICATION . 'controller/' . $controller . '.php';
$class = 'controller' . preg_replace('/[^a-zA-Z0-9]/', '', $controller);
if (file_exists($file)) {
include_once($file);
$this->registry->set('controller_' . str_replace('/', '_', $controller), new $class($this->registry));
} else {
trigger_error('Error: Could not load controller ' . $controller . '!');
exit();
}
}
Now you can do this:
$this->load->controller('catalog/example');
$result = $this->controller_catalog_example->myMethod($var1, $var2, $var3);
Upvotes: 0
Reputation: 14862
In OpenCart 1.5.*, getChild
is used to load other controllers. Specifically, it is running a route to the desired controller and function. For example, common/home
would load the home
controller from the common
group/folder. By adding a third option we specify a function. In this case, 'add' - checkout/cart/add
.
class ControllerModuleModule1 extends Controller {
protected function index() {
ob_start();
$this->getChild('checkout/cart/add');
$this->response->output();
$response = ob_get_clean();
}
}
Most controllers don't return or echo anything, but specify what to output in the $this->response
object. To get what is being rendered you need to call $this->response->output();
. In the above code $response
is the json string that checkout/cart/add
echos.
Upvotes: 3
Reputation: 87
To solve the same issue, I use $this->load->controller("checkout/cart/add").
If I use getChild, this exception get thrown : "Call to undefined method Loader::getChild()".
What is the difference between the 2 methods? Is getChild better?
Upvotes: 2