OpenCart Call Different Controller

北慕城南 提交于 2019-12-11 06:41:10

问题


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


回答1:


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.




回答2:


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?




回答3:


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);


来源:https://stackoverflow.com/questions/27017144/opencart-call-different-controller

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!