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 MVC-L: how the controller, model, template and language are connected

How the MVC-L architecture works in OpenCart 3.0 and 4.1: routing, controller, model, Twig template and language file, naming and path rules, common mistakes.

12 min read OC 3.0 OC 4.1

OpenCart MVC is really MVC-L: each page or module is built from four parts. The controllerCode that receives a request and prepares data. More in the glossary → (Controller) receives the request and manages the work. The model (Model) talks to the database. The Twig template (View) renders the HTML. The language fileA PHP file with interface texts, separate for each language. More in the glossary → (Language) stores the texts. All four parts are linked through the parameter route and identical relative paths, so once you know the route, you immediately know where each file is.

Examples are for OpenCart 4.1; in 4.0.x, model triggers and event handling differ.

What is MVC-L in OpenCart and why is there an "L"?

Classic MVC separates logic, data, and presentation. OpenCart adds a fourth layer: language files. The reason is practical: a store is almost always multilingual. In Ukraine, that means at least Ukrainian, and often English as well. Interface texts are moved into separate PHP arrays so that templates and controllers contain no hard-coded strings.

The key idea: all parts of one page share the same relative path. For a product pageThe page for a single product: photos, price, options, description, reviews. More in the glossary →, this is product/product. The controller, language file, and template are located along it. The model usually has its own path based on the entity, for example catalog/product. This convention is the main "glue" of the architecture: there are no route registries or XML configs, only file paths.

LayerOpenCart 3.0OpenCart 4.1
Controllercatalog/controller/product/product.php, class ControllerProductProductcatalog/controller/product/product.php, class Opencart\Catalog\Controller\Product\Product
Modelcatalog/model/catalog/product.php, class ModelCatalogProductcatalog/model/catalog/product.php, class Opencart\Catalog\Model\Catalog\Product
Templatecatalog/view/theme/default/template/product/product.twigcatalog/view/template/product/product.twig
Languagecatalog/language/en-gb/product/product.phpcatalog/language/en-gb/product/product.php

The admin panel is structured the same way, only in the admin/ directory. The storefrontWhat the customer sees: the home page, categories, product page, and cart. More in the glossary → and the admin are two separate applications on a shared core; for more detail, see the article about admin and catalog in OpenCart. The overview of the file structure of OpenCart 3.0 and 4.1 gives the general map of directories.

How does a request reach the controller via the route?

Every HTTP request passes through index.php. Then the core initializes the registry, config, database, session, and language, and then runs startup actions. Among them is SEO URL, which converts a "pretty" address into route. The full path from the first line to the method call is covered in the article about framework.php and the request path. What matters here is how route is converted into a class and method.

flowchart TD
    A["Request: index.php?route=..."] --> B["framework.php: registry, config, DB, session"]
    B --> C["Startup: SEO URL, language, currency"]
    C --> D["Router: route → controller file and method"]
    D --> E["Controller: load->language, load->model"]
    E --> F["Model: $this->db->query()"]
    F --> E
    E --> G["load->view: Twig + $data"]
    G --> H["Response: setOutput and HTML output"]

OpenCart 3.0: the route checkout/cart/add is parsed as follows. The core looks for the file checkout/cart.php, and if no such file exists, it treats the last segment as the method name (add). Without a method, index() is called.

OpenCart 4.1: the method is separated by a dot (checkout/cart.add); the old separator | is automatically replaced with a dot. The file path and the method are no longer confused, and the class is found by its namespace.

Routing nuances (prohibiting calls to "private" methods, 404 handling, version differences) are collected in a separate article in the section about route=. To understand MVC-L, it is enough to remember that a route is the path to the controller file plus, if needed, a method.

What does the controller do and how does it pull in the other layers?

The controller is the conductor. It knows almost nothing about SQL or HTML. It loads the language, calls the model, assembles the $data array, and passes it to the template. All services ($this->db, $this->config, $this->session, $this->load) are available through magic properties that are read from the OpenCart object registry.

Here is a minimal storefront module that outputs a product list. First, the version for 3.0:

Example

<?php
class ControllerExtensionModuleHello extends Controller {
    public function index($setting) {
        $this->load->language('extension/module/hello');
        $this->load->model('extension/module/hello');

        $data['heading_title'] = $this->language->get('heading_title');
        $data['items'] = $this->model_extension_module_hello->getItems((int)$setting['limit']);

        return $this->load->view('extension/module/hello', $data);
    }
}

The same controller for 4.1, if the extension is called mymodule:

Example

<?php
namespace Opencart\Catalog\Controller\Extension\Mymodule\Module;

class Hello extends \Opencart\System\Engine\Controller {
    public function index(array $setting): string {
        $this->load->language('extension/mymodule/module/hello');
        $this->load->model('extension/mymodule/module/hello');

        $data['heading_title'] = $this->language->get('heading_title');
        $data['items'] = $this->model_extension_mymodule_module_hello->getItems((int)$setting['limit']);

        return $this->load->view('extension/mymodule/module/hello', $data);
    }
}

Note: a module in a layout is called as a child controller, so it returns a string via return rather than calling $this->response->setOutput(). The "main" controller of a page does the opposite. It collects the parts via $this->load->controller('common/header') and hands the result to the Response object. If you confuse these roles, you will get either an empty block or a page that is output twice.

How is the model connected to the controller and the database?

The model is the only place where SQL should live. The call $this->load->model('catalog/product') includes the file model/catalog/product.php. Then the object is registered in the registry under a key obtained by replacing slashes with underscores: model_catalog_product. Hence the access $this->model_catalog_product->getProduct($id). The loading mechanics are described in the article about the Loader and the load->model, view, language methods.

Example (OpenCart 4.1; in 3.0 it is the class ModelExtensionModuleHello extends Model without a namespace)

<?php
namespace Opencart\Catalog\Model\Extension\Mymodule\Module;

class Hello extends \Opencart\System\Engine\Model {
    public function getItems(int $limit): array {
        $query = $this->db->query("SELECT p.`product_id`, pd.`name` FROM `" . DB_PREFIX . "product` p LEFT JOIN `" . DB_PREFIX . "product_description` pd ON (p.`product_id` = pd.`product_id`) WHERE p.`status` = '1' AND pd.`language_id` = '" . (int)$this->config->get('config_language_id') . "' LIMIT " . (int)$limit);

        return $query->rows;
    }
}

A few things worth knowing:

  • The model is called through a proxy. The Loader wraps the model so that events can fire before and after each method: in 3.0 this is catalog/model/catalog/product/getProduct/before (slash before the method), in 4.1 it is catalog/model/catalog/product.getProduct/before (dot before the method). Because of this, third-party modules can substitute data without touching the model file. A trigger with the wrong separator simply won't fire, and no error will be shown.
  • Storefront and admin models are different. admin/model/catalog/product.php can add and edit products, while the storefront version only reads. The admin model cannot be included from a storefront controller, and that is correct.
  • Escaping is your responsibility. $this->db->escape() for strings, casting with (int) for numbers. The mysqli driver has no public API for prepared statements (in 4.1 the pdo driver uses prepare() only internally). Therefore, in both branches, cast numbers to the proper type, escape strings, and validate column names against a whitelist.

The article in the section on models and $this->db explains queries, DB_PREFIX, $query->row, and $query->rows in more depth.

How do the Twig template and the language file receive data?

The template receives only what the controller placed in $data. Each array key becomes a Twig variable: $data['items'] becomes {{ items }}. The template should contain as little logic as possible: loops, conditions, and output.

Example

<div class="hello-module">
  <h3>{{ heading_title }}</h3>
  {% if items %}
    <ul>
      {% for item in items %}
        <li>{{ item.name }}</li>
      {% endfor %}
    </ul>
  {% else %}
    <p>{{ text_empty }}</p>
  {% endif %}
</div>

The language file is a regular PHP array $_:

Example: catalog/language/uk-ua/extension/module/hello.php (3.0)

<?php
$_['heading_title'] = 'Нові надходження';
$_['text_empty']    = 'Поки що товарів немає.';

Here lies a nuance that often causes confusion. The template contains {{ text_empty }}, although the controller did not pass it explicitly. The core has an event on view/*/before that mixes into the template data all strings loaded via load->language(), if such a key is not yet present in $data. That is why many language variables in core templates have no explicit assignment. You can rely on this. But if a value from $data and a language string share the same key, $data wins, and this is worth keeping in mind.

OpenCart 3.0: storefront templates are located in the theme folder (catalog/view/theme/default/template/...). If your theme does not have a file, it is taken from default.

OpenCart 4.1: base templates are located in catalog/view/template/, and themes are supplied as extensionsAdditional functionality: a module, a payment or shipping method, a feed, or a theme. They are managed in "Extensions → Extensions." More in the glossary → and replace templates through events. Extension templates are located in extension/<назва>/catalog/view/template/.

Compiled Twig templates are cached in the storage directory. If changes in .twig are not visible, start with it. Details are in the article about the storage directory, cache, and modifications. You can translate strings without editing files via "Design → Language Editor". Overrides are stored in the database and take priority over the file.

Translation editor: language string overrides on top of files
Translation editor: language string overrides on top of files · OpenCart 4.1.0.4

How do you organize the files of your own module so that everything connects?

Most errors like "Could not load model" or "Error: Could not load template" come from a mismatch between the path in the load->... call and the actual file path. Stick to a simple scheme.

OpenCart 3.0: module in shared folders

  1. Admin controller: admin/controller/extension/module/hello.php, class ControllerExtensionModuleHello.
  2. Admin language: admin/language/en-gb/extension/module/hello.php (and uk-ua, if the language is installed).
  3. Admin template: admin/view/template/extension/module/hello.twig.
  4. Storefront: catalog/controller/extension/module/hello.php, catalog/model/extension/module/hello.php, catalog/language/.../extension/module/hello.php, catalog/view/theme/default/template/extension/module/hello.twig.

OpenCart 4.1: module as a separate extension

  1. Everything is in one folder: extension/mymodule/. Inside are the subfolders admin/ and catalog/ with the usual structure controller, model, language, view/template.
  2. The namespace is built from the path: Opencart\Admin\Controller\Extension\Mymodule\Module for extension/mymodule/admin/controller/module/hello.php.
  3. In core calls, the extension name follows extension/: load->view('extension/mymodule/module/hello').
  4. The extension is packed into an .ocmod.zip archive and installed via "Extensions → Installer".

After installation, the module appears in "Extensions → Extensions" if "Modules" is selected in the type filter. The "Install" button calls the install() method of your admin controller. This is usually where tables are created and events are registered. The access and modify permissions for the current user's group are granted automatically by the core in both branches. Other groups are granted them as needed via the addPermission() method of the user/user_group model. When uninstalling, 3.0 removes the module's permissions from all groups, while 4.1 does not remove them.

Extensions → Extensions (type: Modules): your module appears here, with the «Install» / «Edit» buttons
Extensions → Extensions (type: Modules): your module appears here, with the «Install» / «Edit» buttons · OpenCart 4.1.0.4

Typical pitfalls when organizing files:

  • The class name does not match the path. In 3.0, ControllerExtensionModuleHelloWorld corresponds to the file hello_world.php, because underscores from the path are removed.
  • The language file exists only in en-gb, but the store runs in Ukrainian. If there is no language file in uk-ua, in 3.0 English strings from en-gb will be shown. In 4.1, en-gb is not loaded as a fallback, so without a file in uk-ua, the keys themselves will be displayed instead of the text (heading_title, etc.). To have the interface in Ukrainian, add the translation to uk-ua.
  • In 4.1, the autoloader will not find a class if the namespace does not match the file path. It is advisable to specify return types for compatibility with the core, but they do not affect class loading.
  • In the admin panel, links without user_token redirect to login. Build them via $this->url->link() with the session token. There is a separate article on protecting the panel in general: OpenCart admin security.

How does MVC-L in OpenCart 3.0 differ from 4.1 in practice?

The idea is the same, but the "mechanics" in 4.1 have become stricter and closer to modern PHP. Here is a short list of changes that most often break migrated modules:

AspectOpenCart 3.0OpenCart 4.1
Class namesConcatenated from the path: ControllerCatalogProductNamespaces: Opencart\Admin\Controller\Catalog\Product
Method in routecatalog/product/editcatalog/product.form (the old | is automatically replaced with a dot)
Saving forms in adminPOST to the same page, validation and redirectAJAX to the .save method, response in JSON
Module locationScattered across admin/ and catalog/One extension/<назва>/ folder
ThemesFolder in catalog/view/theme/Extension of type "theme", replaced via events

Because of these differences, a module from 3.0 will not work in 4.1 by simply copying it. You need to rename the classes, rewrite the routes, move the files into the extension folder, and rework the admin form for AJAX. The storefront logic (SQL in models, Twig templates, language arrays) transfers almost unchanged, and this is the best argument for keeping it clean and separated. If such a migration is needed on a live store without risk, you can hand it over to OpenCart fixes and bug-fixing services. But with this article and the core documentation, it is entirely feasible to do it on your own.

Summary

  • OpenCart MVC is MVC-L: the controller manages, the model works with the DB, the Twig template outputs HTML, and the language file stores the texts.
  • The parts are connected by a path convention, not configs. The route determines the controller file, which through $this->load pulls in the language, model, and template.
  • Models are registered as model_шлях_через_підкреслення and called through a proxy, so events can be attached to them.
  • Child controllers return a string; main controllers output through the Response.
  • In 4.1, there are namespaces, a dot as the method separator in routes, modules in a separate extension/ folder, and AJAX form saving.

Next, go through the articles in the section one by one: routing, controllers, models, Twig, and language files. They are all collected on the section page MVC-L: controllers, models, templates. The best practice is to write a small module like the example above for your version right away and make sure all four layers find each other.

FAQ

Can you write SQL queries directly in the controller, without a model?
Technically yes, since $this->db is also available in the controller. But then you lose model events, code reuse and clean migration between versions, so it's best to keep SQL in the model.
Why don't changes to the .twig file show up on the site?
Most often the cause is the cache of compiled templates or modifications in the storage directory, or the theme cache. Clear the cache in the admin control panel and refresh the modifications. In 3.0, also check that the file is in the active theme's folder.
How do you change the template or data of a standard controller without editing the core?
Register an event on the needed trigger, for example view/product/product/before or controller/.../after, and change the data or output in the handler. The alternative is an OCMOD modification, but events are more stable during updates.
Is it necessary to create a language file if the store is only in Ukrainian?
Yes, it's recommended. Without it, the texts would have to be hardcoded into the template, and any second language or translation via the Language Editor would become impossible without rewriting code.
Will my 3.0 controllers work in OpenCart 4.1 if I just copy the files?
No. In 4.1 classes are looked up by namespaces, and modules must be located in the extension// folder. So controllers and models need to be renamed and moved, and routes with methods rewritten to use a dot.
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.