mariobros mariobros - 1 year ago 188
PHP Question

Opencart: call method from another controller

I need to call in checkout/confirm.tpl file a custom function that i've made in controller/product.php

what's the best way to make this?

i've tried this, but doesn't work:

$productController = $this->load->model('product/product');

Answer Source
  1. MVC
    • in an MVC architecture, a template serves solely for rendering/displaying data; it shouldn't (*) call controller/model functions nor it shouldn't execute SQL queries as I have seen in many third-party modules (and even in answers here at SO).
  2. $productController = $this->load->model('product/product');
    • nifty eye has to discover that you are trying to load a model into a variable named by controller and you are also trying to use it in such way. Well, for your purpose there would have to be a method controller() in class Loader - which is not (luckily)
  3. How it should be done?
    • sure there is a way how to access or call controller functions from within templates. In MVC a callable function that is invoked by routing is called action. Using this sentence I can now say that you can invoke an action (controller function) by accessing certain URL.

So let's say your controller is CatalogProductController and the method you want to invoke is custom() - in this case accessing this URL

you will make sure that the custom() method of CatalogProductController is invoked/accessed.

You can access such URL in many ways - as a cURL request, as a link's href or via AJAX request, to name some. In a PHP scope even file_get_contents() or similar approach will work.

(*) By shouldn't I mean that it is (unfortunately) possible in OpenCart but such abuse is against MVC architecture.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download