Skip to content
Tutorials Center
My learning

Topics

Lesson 11 of 27 ยท Extension types

Modules and Layouts

Build an OpenCart 4 module extension: the catalog controller, layout positions, the layout_module table, several instances with their own settings, and caching.

A module is the OpenCart name for a widget: a banner, a "featured products" strip, a newsletter box, a category menu. A module is a small extension that renders HTML and can be dropped into any page by an administrator, without code changes. The merchant chooses where it appears, in which order, and often how many copies of it exist with different settings.

That flexibility rests on two ideas. First, a layout describes a page type (home, product, category, checkout) and has several positions such as content_top and column_left. Second, the table layout_module connects a layout and a position to a module code. When a page renders, the core reads the rows for the matching layout and asks each module to produce its HTML. In this lesson you will build the pieces of a module, see how positions and sort order work, how several instances of one module are stored, how to pass data to Twig, and how to cache the result. The OpenCart code is read-only because it needs a running store; the examples you can run are stand-ins in plain PHP. Read Admin Settings Forms for the admin side and Twig Views and Language Files for templates.

Files of a module

A module called banner from vendor acme has an admin half and a catalog (storefront) half:

TEXT
extension/acme/admin/controller/module/banner.php        settings form, save, install
extension/acme/admin/language/en-gb/module/banner.php
extension/acme/admin/view/template/module/banner.twig
extension/acme/catalog/controller/module/banner.php      renders the widget
extension/acme/catalog/language/en-gb/module/banner.php
extension/acme/catalog/view/template/module/banner.twig

After installing, it shows up under Extensions, Modules. Installing is described in Install, Uninstall and Permissions. A module only appears on the storefront when two things are true: its own status is enabled, and an administrator has placed it in a layout position under Design, Layouts.

The catalog controller

The storefront controller of a module has one job: take its settings, return HTML. Notice that its index method receives an argument and returns a string; it does not call $this->response->setOutput, because it is only one part of a larger page.

PHP
<?php
namespace Opencart\Catalog\Controller\Extension\Acme\Module;

class Banner extends \Opencart\System\Engine\Controller {
    public function index(array $setting): string {
        if (empty($setting['status'])) {
            return '';
        }

        $this->load->language('extension/acme/module/banner');

        $data['heading'] = $setting['heading'] ?? '';
        $data['text']    = $setting['text'] ?? '';
        $data['link']    = $setting['link'] ?? '';

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

The $setting array is the module's saved settings. If the module has no instances, the core passes the values it finds under the module's module_banner_* configuration keys. Returning an empty string for a disabled module means the position simply shows nothing. The Twig template prints the variables; remember that Twig escapes output by default, so only mark text as safe on purpose.

TWIG
<div class="acme-banner">
  <h3>{{ heading }}</h3>
  <p>{{ text }}</p>
  {% if link %}<a href="{{ link }}">{{ text_learn_more }}</a>{% endif %}
</div>

Layouts, positions and the layout_module table

Under Design, Layouts the administrator sees a list: Home, Product, Category, Checkout, and so on. Each layout has:

  • one or more routes it applies to (table layout_route), such as product/product for the product page;
  • a list of module placements (table layout_module), each with a code naming the module, a position and a sort_order.

The default theme offers four positions: content_top and content_bottom (above and below the main content), column_left and column_right (the side columns). A custom theme may add others.

When the storefront renders a page, a small controller for each position, such as the one for content_top, does this:

  1. Find the layout whose route matches the current page (and fall back to the default layout if nothing matches).
  2. Select the layout_module rows for that layout and that position, ordered by sort_order.
  3. For each row, check that the module is installed and enabled, call its catalog controller with its settings, and collect the returned HTML.
  4. Output all pieces one after another.
flowchart TD
    R["Request:<br/>product/product"] --> L["Match layout<br/>(layout_route)"]
    L --> M["Select layout_module rows<br/>for each position"]
    M --> S["Order by sort_order"]
    S --> C["Call module controller<br/>index(setting)"]
    C --> H["Concatenate HTML<br/>for that position"]
    H --> P["Page template prints<br/>content_top, column_left, ..."]

Each position is filled by looking up the rows for the layout, sorting them and asking every module for its HTML.

This design has a consequence worth remembering: a module can do real work (queries, remote calls) on every page that shows it. Keep that work small, or cache it.

Several instances with their own settings

A banner module is more useful if the merchant can create three of them: one for the home page with a seasonal message, another for the cart page. OpenCart supports this with the module table. Each row is one instance: a module_id, a name, the extension code it belongs to, and a setting column holding the instance's settings as JSON.

On the admin side, the module's controller reads an optional module_id from the URL. Without it the form creates a new instance; with it, the form edits that instance. The save method calls the setting/module model: addModule for a new instance and editModule for an existing one. Exact signatures differ slightly between 4.0.x versions, so read admin/model/setting/module.php of the version you target.

In the layout editor the administrator then picks, per position, a specific instance. In 4.0.x the stored code of such a placement has parts separated by dots that identify the extension, the module and the instance, and the position controller splits it to find which controller to call and which module row to load. Treat that format as an internal detail of your version: use the Layouts screen and the core position controllers rather than writing those rows yourself.

When a module has only global settings and no instances (for example a "currency switcher" with just a status flag), it stores its values in setting under module_<name>_* keys, as in Admin Settings Forms, and appears in the layout editor as a single entry.

Passing data to Twig

The controller builds an array and hands it to $this->load->view. Some practical rules:

  • Prepare, don't compute, in Twig. Do queries and formatting in PHP, and keep the template to loops and ifs.
  • Escape user-provided text. The merchant's heading is still data; Twig escapes it unless you use |raw. Only allow |raw for HTML you sanitized.
  • Use language keys for fixed text such as "Learn more", so the module can be translated.
  • Return early when there is nothing to show, so an empty module does not output an empty wrapper that breaks the layout.

Caching a module

If your module runs a query that rarely changes, store the finished data with the cache object. The key must include everything the result depends on, usually the language and the instance:

PHP
$key = 'acme.banner.' . (int)$this->config->get('config_language_id') . '.' . (int)($setting['module_id'] ?? 0);
$data = $this->cache->get($key);

if (!$data) {
    $data = $this->buildData($setting);   // the expensive part
    $this->cache->set($key, $data);       // expires after the configured lifetime
}

Two cautions. Never put per-customer content (names, cart contents, prices that depend on a customer group) into a shared cache entry. And when the merchant saves new settings, delete your key (or include a version number in it) so the change appears at once. Performance in Extensions covers caching more broadly.

Try it: a layout engine

This stand-in is not OpenCart's code. It reproduces the logic of a page render: layouts match by route, placements come from rows with a position and sort order, disabled modules are skipped, and each module returns HTML.

PHP Rendering modules by position

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The home page shows the banner above the content and the categories on the left; the product page lists the cart box first because of its lower sort_order, and the disabled banner contributes nothing; the contact page falls back to the default layout and shows empty positions.

The second example models instances and the cache. One module code has two instances with their own JSON settings, and the cache saves repeated work until settings change.

PHP Instances with JSON settings and a cache

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The cache key contains the instance id, so two instances never share an entry. Clearing the key when settings change is what makes the merchant's edit visible immediately.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does the index method of a catalog module controller do with its result?

    A module is one part of a bigger page. It returns its HTML string, and the position controller concatenates all the pieces.
  2. 2. Which table connects a layout and a position to a module?

    layout_module stores the layout, the module code, the position and the sort order for each placement.
  3. 3. Why does a cache key for a module usually include the language id and instance id?

    The cached data depends on those values. Without them, the first language or instance rendered would be shown to everyone.
  4. 4. A module is installed and enabled but does not appear on the product page. What is the likely cause?

    A module is only displayed where an administrator has placed it under Design, Layouts. Installing and enabling alone is not enough.

Summary

  • A module is a small extension with an admin form and a catalog controller whose index(array $setting) returns HTML.
  • Layouts match pages by route; layout_module rows place module codes in positions such as content_top and column_left, ordered by sort_order.
  • Modules with instances store each instance as a row in the module table with JSON settings; global modules use module_<name>_* settings.
  • Prepare data in PHP, keep Twig simple, escape merchant text, and return early when there is nothing to show.
  • Cache expensive module data with a key that includes language and instance, never per-customer data, and clear it on save.

Next, build a more demanding extension type in Building a Payment Extension.