# 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.

Джерело: https://opencartcode.com/en/wiki/dev-mvc/opencart-mvc
OpenCart: 3.0, 4.1
Оновлено: 2026-11-25

OpenCart MVC is really MVC-L: each page or module is built from four parts. The [controller](https://opencartcode.com/en/wiki/glossary/e-commerce-glossary#controller) (Controller) receives the request and manages the work. The model (Model) talks to the database. The Twig template (View) renders the HTML. The [language file](https://opencartcode.com/en/wiki/glossary/e-commerce-glossary#language-file) (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 page](https://opencartcode.com/en/wiki/glossary/e-commerce-glossary#product-page), 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.

| Layer | OpenCart 3.0 | OpenCart 4.1 |
| --- | --- | --- |
| Controller | `catalog/controller/product/product.php`, class `ControllerProductProduct` | `catalog/controller/product/product.php`, class `Opencart\Catalog\Controller\Product\Product` |
| Model | `catalog/model/catalog/product.php`, class `ModelCatalogProduct` | `catalog/model/catalog/product.php`, class `Opencart\Catalog\Model\Catalog\Product` |
| Template | `catalog/view/theme/default/template/product/product.twig` | `catalog/view/template/product/product.twig` |
| Language | `catalog/language/en-gb/product/product.php` | `catalog/language/en-gb/product/product.php` |

The admin panel is structured the same way, only in the `admin/` directory. The [storefront](https://opencartcode.com/en/wiki/glossary/e-commerce-glossary#storefront) and the admin are two separate applications on a shared core; for more detail, see the article about [admin and catalog in OpenCart](https://opencartcode.com/en/wiki/dev-architecture/opencart-admin-catalog). The overview of [the file structure of OpenCart 3.0 and 4.1](https://opencartcode.com/en/wiki/dev-architecture/opencart-file-structure) 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](https://opencartcode.com/en/wiki/dev-architecture/opencart-framework-php). What matters here is how `route` is converted into a class and method.

```mermaid
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](https://opencartcode.com/en/wiki/dev-architecture/registry-opencart).

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

Example

```php
<?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
<?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](https://opencartcode.com/en/wiki/dev-architecture/opencart-request-response). 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](https://opencartcode.com/en/wiki/dev-architecture/opencart-loader).

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

```php
<?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

```twig
<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
<?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 [extensions](https://opencartcode.com/en/wiki/glossary/e-commerce-glossary#extensions) 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](https://opencartcode.com/en/wiki/dev-architecture/opencart-storage). 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 · 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 · OpenCart 4.1.0.4

> Do not edit core files for the sake of your module: controllers in `catalog/controller/product/`, models in `catalog/model/catalog/`, and so on. The next update will overwrite everything. Interfere with other controllers, models, and templates through events (OpenCart 3.0 and 4.1) or OCMOD.

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](https://opencartcode.com/en/blog/bezpeka-adminki-opencart-zaxist-paneli-vid-zlamu).

## 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:

| Aspect | OpenCart 3.0 | OpenCart 4.1 |
| --- | --- | --- |
| Class names | Concatenated from the path: `ControllerCatalogProduct` | Namespaces: `Opencart\Admin\Controller\Catalog\Product` |
| Method in route | `catalog/product/edit` | `catalog/product.form` (the old `\|` is automatically replaced with a dot) |
| Saving forms in admin | POST to the same page, validation and redirect | AJAX to the `.save` method, response in JSON |
| Module location | Scattered across `admin/` and `catalog/` | One `extension/<назва>/` folder |
| Themes | Folder 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](https://opencartcode.com/en/marketplace/product/opencart-fixes). But with this article and the core documentation, it is entirely feasible to do it on your own.

> Looking for where a particular part of a page is generated? Take `route` from the address (or from the SEO URL table), and you will immediately find the controller, language file, and template with the same path. The model will be indicated by `load->model()` inside the controller.

## 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](https://opencartcode.com/en/wiki/dev-mvc). 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.
