# OpenCart Coding Standards: Module Style and Structure That Are Easy to Maintain

> OpenCart coding standards for 3.0 and 4.1 modules: core conventions, thin controllers and models, key prefixes, language files, migrations, versions, and what to check before every release.

Джерело: https://opencartcode.com/en/wiki/dev-practice/opencart-coding-standards
Оновлено: 2026-11-25

OpenCart coding standards are not a separate document. They are a set of conventions that the core itself follows: the MVC-L structure, file and class names derived from the route, prefixes for language keys and settings, tabs for indentation, and `$data` for templates. A module written to these conventions is easy for any OpenCart developer to read, survives core updates, and can be moved between 3.0 and 4.1 with minimal changes. Below are the rules that make a module easy to maintain in practice, and an explanation of why each one matters in OpenCart.

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

## Which core conventions should you follow?

The simplest rule: write the way your version's core code is written. Then a colleague who knows OpenCart can find their way around your module without documentation.

- **Tab indentation.** The core of both versions is formatted with tabs. If a module uses spaces, diffs against the core and third-party modifications become unreadable.
- **Variable and key names in snake_case**: `$product_info`, `$data['button_save']`, `module_mymod_status`. Class methods use camelCase (`getProducts`, `editSetting`).
- **File names in lowercase with underscores**, because the route and the class name are built from them. `my_module.php` gives the route `extension/module/my_module` in 3.0, and the class `ControllerExtensionModuleMyModule`. In 4.1 the class is `MyModule` within the package namespace.
- **Template data only through `$data`**, with no global variables and no calls to models from Twig.
- **Types in 4.1.** Core 4.1 declares parameter and return types (`public function index(): void`, `getProducts(array $data = []): array`). Do the same in modules for 4.1. In 3.0 the core has almost no types, and 3.0.4.1 runs on PHP 7.3, so typed properties are not available there.

How the controller, model, template, and [language file](https://opencartcode.com/en/wiki/glossary/e-commerce-glossary#language-file) are connected is explained in the article about [MVC-L in OpenCart](https://opencartcode.com/en/wiki/dev-mvc/opencart-mvc), and the file layout of the package is covered in the article about [extension anatomy](https://opencartcode.com/en/wiki/dev-extensions/opencart-module-structure).

## How do you divide logic between the controller, model, and template?

Most modules that are hard to maintain share one trait: a "fat" controller that mixes SQL, API calls, calculations, and HTML generation. Divide responsibilities like this:

| Layer | What it does | What it does not do |
| --- | --- | --- |
| Controller | reads the request, checks permissions and tokens, calls models, prepares `$data`, chooses the template or JSON | does not write SQL, does not run business logic spanning dozens of lines |
| Model | all database queries, with type casting and escaping | does not read `$this->request`, does not generate HTML |
| Module library | external API client, calculations, data transformation | does not depend on the OpenCart registry unless necessary |
| Template | markup, loops over ready data, output escaping | does not contain data selection logic or calculations |
| Language file | all interface texts | does not contain HTML or logic or settings |

A model that does not read `$this->request` but receives parameters as arguments can be called the same way from a controller, an event handler, a cron job, or an API. A library with no OpenCart dependencies is the foundation of a module that supports both branches (see the article on [module compatibility with 3.0 and 4.1](https://opencartcode.com/en/wiki/dev-practice/opencart-module-compatibility-3-4)). How a controller passes data to the template and calls child controllers is described in the article on the [OpenCart controller](https://opencartcode.com/en/wiki/dev-mvc/opencart-controller).

Example: a thin [storefront](https://opencartcode.com/en/wiki/glossary/e-commerce-glossary#storefront) controller (OpenCart 4.1)

```php
public function index(array $setting): string {
    $this->load->language('extension/mymod/module/mymod');
    $this->load->model('extension/mymod/module/mymod');

    $items = $this->model_extension_mymod_module_mymod->getItems((int)$setting['limit'], (int)$this->config->get('config_language_id'));

    if (!$items) {
        return '';
    }

    $data['heading_title'] = $setting['name'];
    $data['items'] = [];

    foreach ($items as $item) {
        $data['items'][] = [
            'name' => $item['name'],
            'href' => $this->url->link('product/product', 'language=' . $this->config->get('config_language') . '&product_id=' . $item['product_id'])
        ];
    }

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

## How do you name settings, tables, events, and language keys?

In OpenCart, the keys of all modules live in shared tables and namespaces. Prefixes are not a matter of taste. They protect against conflicts and data loss.

### Settings

The settings group code is built from the extension type and the module code: `module_mymod`, `payment_mymod`, `shipping_mymod`, and every key starts with it (`module_mymod_status`, `module_mymod_limit`). This is a requirement, not a style choice. `editSetting()` in both versions first deletes the entire `code` group for the store, then inserts only keys that start with `code`. A form field without the prefix simply will not be saved. Details are in the article on [module settings](https://opencartcode.com/en/wiki/dev-extensions/opencart-module-setting).

### Tables, events, cache, logs

- Tables: `DB_PREFIX . 'mymod_...'`, never without `DB_PREFIX`. Stores with a prefix other than `oc_` are more common than you might think.
- Event codes: `mymod_...`, so that `deleteEventByCode()` removes exactly your events on uninstall.
- Cache keys: start with `mymod.` so they do not collide with core keys.
- Logs: a separate file `mymod.log`.

### Language keys

The core uses fixed prefixes: `heading_title` for headings, `text_` for regular texts, `entry_` for field labels, `help_` for hints, `button_` for buttons, `column_` for table column headers, and `error_` for errors. Follow them, so a translator immediately knows where a string is displayed. In 4.1, include a complete language file for every language the module supports, because there is no fallback `en-gb` there as in 3.0. How language loading works is described in the article on [language files](https://opencartcode.com/en/wiki/dev-mvc/opencart-language-files).

## How do you handle installation, updates, and versions?

A maintainable module knows how not only to install, but also to update without reinstalling and to uninstall without leaving traces.

1. **One version point.** Keep the module version number in one place (a class constant, or `install.json` in 4.1, where the core expects the `name`, `version`, `author`, and `link` fields), and show it on the settings page.
2. **Migrations instead of "reinstall the module".** Store the installed version in the module settings, and when the settings page is opened (or in `install()`), run migration steps from the saved version to the current one: add a column, move data, register a new event. Each step must be safe to run again (`CREATE TABLE IF NOT EXISTS`, check that the column exists before `ALTER`).
3. **`uninstall()` removes everything of yours**: events by code, cron tasks in 4.1, settings. Delete your own tables only when the user explicitly wants that, because order or binding data may be needed after a reinstall.

What `install()` and `uninstall()` do, and in what order, in each version is covered in the article on [module install and uninstall](https://opencartcode.com/en/wiki/dev-extensions/install-opencart-module). The rules for custom tables are in the article on [module tables](https://opencartcode.com/en/wiki/dev-extensions/opencart-module-tables).

> Keep a changelog (CHANGELOG) for the module in the repository and in the release description. When a customer writes "it stopped working after the update," a log listing the changed events and tables saves hours of searching.

## What should you avoid so you don't break other people's sites?

- **Edits to core files.** A core file changed by hand is lost on update and conflicts with other modules. Use events, and in 3.0, where events are not available, use OCMOD with precise searches.
- **Broad OCMOD searches.** A search for a generic string like `</head>` or `$data['footer']` conflicts with dozens of other modifications. Search for the most unique fragment possible.
- **Global state.** Do not change core keys of `$this->config` "on the fly", and do not overwrite registry objects (`db`, `cache`, `session`) with your own. Other modules depend on them.
- **Dependencies in shared locations.** Put Composer libraries inside the module package with their own autoloader, not in the core `storage/vendor/`.
- **Silent failures.** `@` before a call and an empty `catch` hide problems that are then hunted for weeks. Write the reason to the module log.
- **Hardcoded addresses and IDs.** `store_id` 0, `language_id` 1, the store domain, or [order status](https://opencartcode.com/en/wiki/glossary/e-commerce-glossary#order-status) 5 in code break on multistore, in another language, or with a different set of statuses. Take them from the config or module settings.

## What should you check before each release?

- `php -l` on all PHP files on the minimum [PHP version](https://opencartcode.com/en/wiki/glossary/e-commerce-glossary#php-version) of each supported release: 7.3 for 3.0.4.1, 8.1 for 3.0.5.1 and 4.1.0.4.
- Clean installation, update from the previous version, uninstallation, and reinstallation.
- Working with a [table prefix](https://opencartcode.com/en/wiki/glossary/e-commerce-glossary#table-prefix) other than `oc_`, in a second language, and on a second store.
- The error log is empty after the main scenarios have been run: no Notices from the module.
- No debugging code, temporary logs, or test keys.
- Output is escaped, SQL uses types and escaping, and admin actions check `modify`. A detailed checklist is in the article on [module security](https://opencartcode.com/en/wiki/dev-practice/opencart-module-security).
- Language files are complete for all declared languages.

## Summary

- Write the way your version's core is written: tabs, snake_case for data, files named from the route, `$data` for templates, types in 4.1.
- The controller is thin, SQL lives only in models, business logic is in a library without registry dependencies, and the template contains no logic.
- Use the module prefix everywhere: settings (mandatory for `editSetting()`), tables with `DB_PREFIX`, event codes, cache keys, logs, and language keys following core conventions.
- One version point, migrations instead of reinstallation, `uninstall()` without traces.
- Do not edit the core, do not run broad OCMOD searches, do not hide errors, and do not hardcode IDs.
- Before release: linter on the minimum PHP version, installation and update, a different prefix, language, and store, and an empty error log.

Other materials on debugging, performance, and module code quality are collected in the section ["Debugging, Performance, and Code Quality"](https://opencartcode.com/en/wiki/dev-practice).

## FAQ

**Does OpenCart have an official coding standard like PSR-12?**

There is no mandatory standard for modules; the core's own style serves as the reference. For new classes not tied to the registry, you can follow PSR-12, but files that extend core classes are better formatted like the core.

**Should you cover an OpenCart module with automated tests?**

Yes, at least for a library with business logic: it is easy to test with PHPUnit because it does not depend on the registry. Controllers and models are more convenient to check with scenarios on a test store.

**How do you name a module so it doesn't conflict with others?**

Use a unique code with an author or brand prefix, for example acme_delivery instead of delivery. The code ends up in routes, classes, settings and tables, and it is very hard to change after release.

**Do you need to comment every method?**

No, short docblocks are enough for public methods of models and libraries, plus comments where the code does something non-obvious. Core 4.1 itself uses docblocks with parameter types, and IDEs understand them well.
