No results found

Try a different search query

Popular searches:

Add to Cart

Cart

You have no purchases yet

Browse Marketplace
Original Subtotal:
Product discounts:
Quantity Discount:
Total:
View Cart
MVC-L: controllers, models, templates

OpenCart Controller: Data, Template and Child Controllers in 3.0 and 4.1

How an OpenCart controller collects data in $data, passes it to a Twig template, and embeds child controllers. Differences between 3.0 and 4.1, a working page example, and common mistakes.

11 min read OC 3.0 OC 4.1

The OpenCart controllerCode that receives a request and prepares data. More in the glossary → is a PHP class whose method is called by the route route=. It loads a language fileA PHP file with interface texts, separate for each language. More in the glossary → and models, collects data into the $data array, and passes it to a Twig template. It then either returns the finished HTML as the response or returns it as a string to the parent controller. This article walks through all of that work using the real product card code from OpenCart 3.0 and 4.1. The examples are for OpenCart 4.1; in 4.0.x, model triggers and event handling work differently. We'll also explain how child controllers work (header, footer, columns, modules) and where developers most often make mistakes.

What does an OpenCart controller do and where is it located?

In the MVC-L scheme, the controller is the only part that knows about the request. The model receives parameters and returns arrays from the database. The template only outputs variables. The language file stores strings. The controller brings all of these together. The overall picture of how these pieces relate is described in the article how the controller, model, template, and language are connected, while here we focus on the controller itself.

File locations depend on the version:

  • OpenCart 3.0: catalog/controller/product/product.php for the storefrontWhat the customer sees: the home page, categories, product page, and cart. More in the glossary →, admin/controller/... for the admin. Modules are located in catalog/controller/extension/module/. The class name is built from the route: product/product → ControllerProductProduct.
  • OpenCart 4.1: the core paths are the same, but the class has a namespace. For example, Opencart\Catalog\Controller\Product\Product. ExtensionsAdditional functionality: a module, a payment or shipping method, a feed, or a theme. They are managed in "Extensions → Extensions." More in the glossary → live in a separate directory, extension/<vendor>/catalog/controller/..., and have the namespace Opencart\Catalog\Controller\Extension\<Vendor>\....

For the full directory map, see the article about the file structure of OpenCart 3.0 and 4.1. How the core turns a route string into a class and method is covered in detail in the article about routing with route= in 3.0 and 4.1.

Here is how the beginning of the same controller looks in both branches:

catalog/controller/product/product.php · OpenCart 3.0.5.1 · lines 2–15

class ControllerProductProduct extends Controller {
	private $error = array();

	public function index() {
		$this->load->language('product/product');

		$data['breadcrumbs'] = array();

		$data['breadcrumbs'][] = array(
			'text' => $this->language->get('text_home'),
			'href' => $this->url->link('common/home')
		);

		$this->load->model('catalog/category');

Note the return type ?\Opencart\System\Engine\Action in 4.1. A controller can return an Action object with a different route, for example a 404 page, and the core will execute it instead of the current one. In 3.0, the dispatch loop can also handle a returned Action, but this is not explicitly declared there.

How does the controller get data: $this, models, and the request

Everything you call through $this-> comes from the Registry: load, request, config, db, session, customer, document, url, currency, tax, and others. The base class Controller uses the magic __get to get an object from the registry by name. For more on this, see the article how objects reach the controller through the Registry.

The typical sequence of actions inside a method is as follows:

  1. Language. $this->load->language('product/product') loads the strings, which are then available through $this->language->get('key').
  2. Model. $this->load->model('catalog/product') registers an object named model_catalog_product. Slashes in the name are replaced with underscores.
  3. Input parameters. They are taken from $this->request->get or ->post and always cast to the required type.
  4. Template data. Model results are converted into what needs to be displayed: formatted prices, resized images, links.

Point 3 is clearly visible in the 4.1 product card code:

catalog/controller/product/product.php · OpenCart 4.1.0.4 · lines 17–27

		if (isset($this->request->get['product_id'])) {
			$product_id = (int)$this->request->get['product_id'];
		} else {
			$product_id = 0;
		}

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

		$product_info = $this->model_catalog_product->getProduct($product_id);

		if ($product_info) {

Casting with (int) is mandatory here. The model usually escapes values too, but the controller is the first line of defense, and raw $_GET input must not be trusted. How request and response work is described in the separate article about Request and Response.

Another characteristic detail: the controller does not pass the model array to the template "as is." The price goes through $this->tax->calculate() and $this->currency->format(), and the image goes through model_tool_image->resize(). The template receives strings that are already ready for output. Keep the formatting logic in the controller, not in Twig.

How data gets into the Twig template

Everything the controller puts into $data becomes a template variable: $data['heading_title'] turns into {{ heading_title }}. Rendering is performed by $this->load->view('маршрут/шаблону', $data). The method returns an HTML string and does not output anything itself.

The template path is specified without the extension and without the theme:

  • OpenCart 3.0: $this->load->view('product/product', $data) looks for the file catalog/view/theme/<активна_тема>/template/product/product.twig. If the file is not in the active theme, the default theme is used. The substitution is done by a system theme event.
  • OpenCart 4.1: storefront templates are located in catalog/view/template/. Extension templates are called with a prefix: extension/<vendor>/module/назва.

Why are there no dozens of lines like $data['text_home'] = $this->language->get('text_home') in the product card code? A system language event fires before rendering. It merges all loaded language keys that are not yet in the template data into the data. That's why only the strings that need substitution are manually placed into $data. For example, $data['text_minimum'] = sprintf($this->language->get('text_minimum'), ...). For more on language files, see the article in the section about translating a module.

What are child controllers and how do you call them?

A child controller is an ordinary controller that is called not by URL but from another controller via $this->load->controller('маршрут'). The difference is only at the end of the method. A child controller returns the result of load->view() as a string and does not call setOutput(). The parent controller puts this string into $data and outputs it in its own template.

This is exactly how every storefront page is assembled. Header, footer, column_left, column_right, content_top, and content_bottom are child controllers called with common/. Columns, in turn, call the module controllers assigned to the current layout. The product card shows two more examples: the captcha in 3.0 and the reviews block in 4.1.

catalog/controller/product/product.php · OpenCart 3.0.5.1 · lines 383–388

			// Captcha
			if ($this->config->get('captcha_' . $this->config->get('config_captcha') . '_status') && in_array('review', (array)$this->config->get('config_captcha_page'))) {
				$data['captcha'] = $this->load->controller('extension/captcha/' . $this->config->get('config_captcha'));
			} else {
				$data['captcha'] = '';
			}

catalog/controller/product/product.php · OpenCart 4.1.0.4 · lines 299–301

			$data['rating'] = $product_info['rating'];
			$data['review_status'] = (int)$this->config->get('config_review_status');
			$data['review'] = $this->load->controller('product/review');

In 4.1, reviews are moved into a separate controller, product/review. The product card simply inserts its HTML into {{ review }}. This approach should be adopted in your own modules too: a block that may be needed on several pages should be implemented as a child controller, not copied code.

Passing arguments

A child controller cannot see the parent's $data: it is a different object with a different local variable. Pass everything needed as arguments.

  • OpenCart 3.0: an array is passed as the second parameter of load->controller(), and it becomes the argument of the method. This is how a column passes its settings to a module: the index($setting) method in extension/module/... receives the array of module parameters.
  • OpenCart 4.1: after the route, you can pass any number of arguments. They will go into the method in the same order.

The module layout for pages is configured in Design → Layouts. That is where common/column_left and other positions learn which child module controllers to call.

Page layout: modules in the "Column left" and "Content top" positions, each of which becomes a child controller
Page layout: modules in the "Column left" and "Content top" positions, each of which becomes a child controller · OpenCart 4.1.0.4

How Loader itself works and how load->controller differs from load->view and load->model is explained in the article about the OpenCart Loader.

How a request travels from route= to the finished page

The full cycle from index.php to the controller is described in the article about the request path through framework.php. At the controller level, the sequence is as follows:

flowchart TD
    A["Request ?route=product/product"] --> B["Startup: session, language, currency, SEO URL"]
    B --> C["Event controller/.../before"]
    C --> D["Controller index() method"]
    D --> E["load->language and load->model"]
    E --> F["Collecting the $data array"]
    F --> G["load->controller: header, footer, columns"]
    G --> H["load->view: render Twig to a string"]
    H --> I["response->setOutput"]
    I --> J["Event controller/.../after and output"]

Every load->controller() call, including child ones, passes through the controller/<маршрут>/before and /after events. That means you can change the arguments or the result of any child block through an event, without touching core files. Registered events can be viewed in Extensions → Events.

Events list: triggers such as catalog/controller/.../before and the action that handles them
Events list: triggers such as catalog/controller/.../before and the action that handles them · OpenCart 4.1.0.4

An alternative to events is modifications, which rewrite controller code on the fly. This method is covered in detail in the blog: OCMOD: code changes without modifying system files.

How to write your own page controller: an example for 3.0 and 4.1

Let's create a simple "Shipping and Payment" page on the storefront with the route information/delivery. This is a teaching example, not core code. Three files are needed: the controller, the language file catalog/language/uk-ua/information/delivery.php with keys such as heading_title, text_np, and so on, and the template.

OpenCart 3.0

<?php
// catalog/controller/information/delivery.php
class ControllerInformationDelivery extends Controller {
	public function index() {
		$this->load->language('information/delivery');

		$this->document->setTitle($this->language->get('heading_title'));

		$data['breadcrumbs'] = array();
		$data['breadcrumbs'][] = array(
			'text' => $this->language->get('text_home'),
			'href' => $this->url->link('common/home')
		);
		$data['breadcrumbs'][] = array(
			'text' => $this->language->get('heading_title'),
			'href' => $this->url->link('information/delivery')
		);

		$data['free_from'] = $this->currency->format(1500, $this->session->data['currency']);

		$data['column_left']    = $this->load->controller('common/column_left');
		$data['column_right']   = $this->load->controller('common/column_right');
		$data['content_top']    = $this->load->controller('common/content_top');
		$data['content_bottom'] = $this->load->controller('common/content_bottom');
		$data['footer']         = $this->load->controller('common/footer');
		$data['header']         = $this->load->controller('common/header');

		$this->response->setOutput($this->load->view('information/delivery', $data));
	}
}

Put the template in catalog/view/theme/default/template/information/delivery.twig. The page address is index.php?route=information/delivery.

OpenCart 4.1

<?php
// catalog/controller/information/delivery.php
namespace Opencart\Catalog\Controller\Information;
class Delivery extends \Opencart\System\Engine\Controller {
	public function index(): void {
		$this->load->language('information/delivery');

		$this->document->setTitle($this->language->get('heading_title'));

		$language = 'language=' . $this->config->get('config_language');

		$data['breadcrumbs'] = [];
		$data['breadcrumbs'][] = [
			'text' => $this->language->get('text_home'),
			'href' => $this->url->link('common/home', $language)
		];
		$data['breadcrumbs'][] = [
			'text' => $this->language->get('heading_title'),
			'href' => $this->url->link('information/delivery', $language)
		];

		$data['free_from'] = $this->currency->format(1500, $this->session->data['currency']);

		$data['column_left']    = $this->load->controller('common/column_left');
		$data['column_right']   = $this->load->controller('common/column_right');
		$data['content_top']    = $this->load->controller('common/content_top');
		$data['content_bottom'] = $this->load->controller('common/content_bottom');
		$data['footer']         = $this->load->controller('common/footer');
		$data['header']         = $this->load->controller('common/header');

		$this->response->setOutput($this->load->view('information/delivery', $data));
	}
}

Put the template in catalog/view/template/information/delivery.twig. The language= parameter in links for 4.1 is mandatory: all core controllers do this (see 4.1.0.4, catalog/controller/product/product.php, lines 31–37).

Which differences between 3.0 and 4.1 matter for the controller?

AspectOpenCart 3.0OpenCart 4.1
Class nameControllerProductProduct, no namespaceOpencart\Catalog\Controller\Product\Product
Method call in routeproduct/manufacturer/infoproduct/manufacturer.info (in 4.1 the old | separator is automatically replaced with a dot)
Child controller argumentsA single array as the second parameterAny number of arguments
TypingNoneReturn types, for example ?Action or void
Language in linksNot passedlanguage= in every url->link()
TemplatesThrough the theme: theme/<тема>/template/catalog/view/template/; for extensions, with the extension/<vendor>/ prefix

In 3.0, the core derives the class name simply by removing everything except letters and digits from the route. PHP class names are case-insensitive, so information/delivery_info will find the class ControllerInformationDeliveryInfo. In 4.1, route segments are converted to CamelCase, taking underscores into account, and the namespace must exactly match the file path. An error in namespace is the most common cause of "Class not found" when migrating a module from 3.0.

Common controller mistakes

  • Calling $this->response->setOutput() in a child controller. The method returns nothing to the parent, so the block will not appear on the page. The parent setOutput() is called later and will overwrite this output. A child controller must do return $this->load->view(...).
  • Expecting a child controller to see the parent's variables. It does not see them; pass arguments.
  • Missing (int) for identifiers from $this->request->get.
  • SQL queries directly in the controller. Keep them in the model so the code can be overridden and tested.
  • In the admin: links without user_token and no $this->user->hasPermission() check in save methods. These topics are covered in separate articles in this section.

Summary

  • An OpenCart controller is a class whose method is called by the router or another controller. It takes data from request and models, prepares it for output, and assembles it into $data.
  • $this->load->view() only returns an HTML string. The page sent in response is delivered by $this->response->setOutput(), and only the main controller should call it.
  • Child controllers (header, footer, columns, modules, reviews) return a string that the parent places into $data. Data is passed between them only through arguments.
  • For 4.1, remember the namespace, the dot as the method separator in the route, and language= in links.
  • Change the external behavior of core controllers through before/after events, not by editing files.

Next, it makes sense to move on to models and working with $this->db, to Twig templates, and to AJAX controllers with JSON responses. All of these articles are collected on the section page MVC-L: controllers, models, templates.

FAQ

Can I block direct calls to a controller method through the URL?
The core blocks calling magic methods such as __construct, but a regular public method is reachable via its route. Put helper logic in a private or protected method, or check access conditions at the start of the public method.
How do I debug a controller if the page is just blank?
Turn on error display and logging in the store's server settings, then check the error log in the admin. For custom messages, use $this->log->write(), which writes to the log in the storage directory.
Why don't changes to the controller show up on the site?
Most often a modification overrides the file: OpenCart runs a copy from the modification cache, not your original. Refresh modifications in the admin and clear the template cache, and make sure you are editing the file of the right application — catalog or admin.
Can I call a controller from a model?
Technically the load object is also available in a model, but it is better not to do this: a model should only work with data. If you need a shared block, call a child controller from another controller.
Was this article helpful?
Thanks for your feedback!

Related articles

Didn't find the answer?

Ask the community: OpenCart developers answer on the forum.

Ask on the forum
We use cookies

We use cookies and similar technologies to improve your experience, analyse traffic, and show personalised ads. Read our Cookie Policy for details.