Skip to content
Tutorials Center
My learning

Topics

Lesson 23 of 27 ยท Real-world projects

Project: Product Badge Module with Events

Build a product badge extension for OpenCart: admin rules, badges by stock, newness and sale, event hooks on product lists, scheduling and caching, with a runnable rule engine.

Badges such as "Only 3 left", "New" and "-25%" are small, but they sell. Merchants want them without editing theme files, they want to control them from the admin, and they want them to disappear automatically when a sale ends. This project builds an extension, Acme Badges, that does exactly that using the tools you have learned: an admin rule screen, an event that adds badges to product cards without touching the theme, and the caching rules from Performance in Extensions.

OpenCart cannot run on this site. The extension files are therefore read-only code, while the interesting part, the rule engine that decides which badges a product gets, is plain PHP that runs live below. The HTML injection and the cache are also shown as runnable stand-ins. Similar ideas for other platforms appear in Merchandising and Recommendations.

The design

flowchart TD
    A["Admin rules screen"] --> T["Table acme_badge_rule"]
    T --> RC["Rules cache<br/>(versioned key)"]
    L["Event: product list loaded"] --> P["Preload stock and dates<br/>for the whole page"]
    P --> E["Rule engine<br/>(pure PHP)"]
    RC --> E
    E --> M["Badges per product"]
    V["Event: product card rendered"] --> M
    M --> H["Insert badge HTML<br/>into the card"]

Rules come from the cache, the engine decides, and two events connect it to the storefront without editing templates.

Three principles keep the extension fast and safe:

  1. The engine is pure. It takes a product row, the list of rules and today's date, and returns badge labels. Nothing in it touches the database, so it is easy to test.
  2. Rules are cached; badges are computed. Rules change rarely, so they are cached under a versioned key. Badges depend on stock and today's date, so they are computed on the fly from data already in memory. That avoids stale "Only 3 left" labels.
  3. No query per card. A product page can show 100 cards; the extension must not run 100 queries.

Files

TEXT
extension/acme/
  install.json
  admin/controller/module/badge.php      rules list, form, save, delete
  admin/model/module/badge.php           reads and writes the rule table
  admin/view/template/module/badge.twig
  catalog/controller/event/badge.php     the two event handlers
  catalog/model/module/badge.php         loads rules and product data
  system/library/acme/badge/engine.php   the pure rule engine

Step 1: rules in the database (read-only)

Each rule has a label, a type, one numeric value, a priority (lower numbers win), an optional schedule and a status. The admin screen is an ordinary list-and-form pair like the one in Admin Settings Forms.

SQL
CREATE TABLE IF NOT EXISTS `oc_acme_badge_rule` (
  `rule_id` INT(11) NOT NULL AUTO_INCREMENT,
  `label` VARCHAR(32) NOT NULL,
  `type` VARCHAR(16) NOT NULL,
  `value` INT(11) NOT NULL DEFAULT 0,
  `priority` INT(11) NOT NULL DEFAULT 10,
  `date_start` DATE NULL,
  `date_end` DATE NULL,
  `status` TINYINT(1) NOT NULL DEFAULT 1,
  PRIMARY KEY (`rule_id`),
  KEY `status_priority` (`status`, `priority`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;

The four rule types are:

Type Badge appears when value means
sold_out stock is zero or below unused
low_stock stock is above zero and at most value the stock threshold
new the product was added in the last value days days
sale a special price exists and the discount is at least value percent minimum percent

Any rule can also have a start and end date, so a "Summer deal" rule can switch itself on and off. The table is created in the admin controller's install() and removed in uninstall(), as in Install, Uninstall and Permissions.

Step 2: the rule engine (runnable)

The engine filters the rules to the ones that are active today, tests each against the product, sorts the matches by priority, removes duplicate labels and keeps at most the configured number. Prices are integer cents so percent calculations are exact, as explained in Money as Integers.

PHP A rule engine that picks badges for products

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.

Check the output against the rules. The Tent is both low on stock, new and on sale, but the maximum is two badges and lower priority numbers win, so it shows "Low stock" and "New". The Rain Jacket has a discount of 25% in June, so it shows "Summer deal"; in July the scheduled rule has ended and the badge disappears without anybody touching the admin.

Step 3: connecting to the storefront with events (read-only)

You register two events in install() with the settings event model. The exact array keys and the separator in the action string (a dot before the method in recent 4.0.x releases, a pipe in the earliest ones) depend on your OpenCart version, so copy the pattern from a bundled extension of your target version.

PHP
<?php
public function install(): void {
    $this->load->model('setting/event');

    $this->model_setting_event->addEvent([
        'code'        => 'acme_badge_preload',
        'description' => 'Preload data for badges once per product list',
        'trigger'     => 'catalog/model/catalog/product/getProducts/after',
        'action'      => 'extension/acme/event/badge.preload',
        'status'      => 1,
        'sort_order'  => 1
    ]);

    $this->model_setting_event->addEvent([
        'code'        => 'acme_badge_thumb',
        'description' => 'Add badges to product cards',
        'trigger'     => 'catalog/view/product/thumb/after',
        'action'      => 'extension/acme/event/badge.thumb',
        'status'      => 1,
        'sort_order'  => 1
    ]);
}

public function uninstall(): void {
    $this->load->model('setting/event');
    $this->model_setting_event->deleteEventByCode('acme_badge_preload');
    $this->model_setting_event->deleteEventByCode('acme_badge_thumb');
}

The first event runs once per product list. It receives the list OpenCart just loaded and prepares everything the engine needs for the whole page, so the second event, which runs once per card, does no database work at all.

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

class Badge extends \Opencart\System\Engine\Controller {
    private static array $products = [];

    // After catalog/model/catalog/product/getProducts: $output is the list of products
    public function preload(string &$route, array &$args, mixed &$output): void {
        if (!$this->config->get('module_acme_badge_status') || !is_array($output) || !$output) {
            return;
        }

        $ids = array_map(fn($row) => (int)$row['product_id'], $output);

        // One query for the whole page; check which columns your version's list rows already contain
        $query = $this->db->query("SELECT `product_id`, `quantity`, `date_added` FROM `" . DB_PREFIX . "product`
            WHERE `product_id` IN (" . implode(',', $ids) . ")");

        foreach ($query->rows as $row) {
            self::$products[(int)$row['product_id']] = $row;
        }
        foreach ($output as $row) {
            self::$products[(int)$row['product_id']]['price']   = (int)round((float)$row['price'] * 100);
            self::$products[(int)$row['product_id']]['special'] = $row['special'] ? (int)round((float)$row['special'] * 100) : null;
        }
    }

    // After catalog/view/product/thumb: $args holds the template data, $output the finished HTML
    public function thumb(string &$route, array &$args, mixed &$output): void {
        $id = (int)($args['product_id'] ?? 0);
        if (!isset(self::$products[$id]) || !is_string($output)) {
            return;
        }

        $this->load->model('extension/acme/module/badge');
        $engine = $this->model_extension_acme_module_badge->getEngine();   // rules from the cache

        $labels = $engine->badgesFor([
            'quantity' => (int)self::$products[$id]['quantity'],
            'added'    => substr((string)self::$products[$id]['date_added'], 0, 10),
            'price'    => self::$products[$id]['price'],
            'special'  => self::$products[$id]['special'],
        ]);

        if ($labels) {
            $output = $this->insert($output, $labels);
        }
    }
}

Three details deserve attention. The handler takes its arguments by reference, which is how events let you change data, as explained in Events. It returns early whenever something is missing, because an event handler that throws would break a customer's category page. And thumb never queries the database: it reads from the preload, from the cached rules, and from the clock.

Inserting the badge HTML

Because the card is already rendered when the after event runs, the handler adds markup to the finished HTML string. This is the fragile part: it depends on the theme's card markup. A good implementation looks for one well-known marker (for example <div class="image">), inserts right after it, and does nothing if the marker is missing, so a custom theme loses the badges but never breaks. Labels typed by an administrator are escaped before they go into the page.

PHP Inserting badges safely, with a fallback

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 same event technique can be applied to the product page with a trigger on the product view. Look up the exact trigger name for your version by searching the catalog controller that renders the page, rather than relying on a remembered name.

Step 4: caching the rules

The engine needs the active rules on every page that shows products. Reading them from MySQL each time is a query per request; caching them removes it. The danger is stale rules: the admin edits a badge and the old one stays for an hour. A versioned key solves this without trying to delete files: the key contains a version number stored in a setting, and saving a rule increments the version, so the old cache entry is simply never read again.

PHP
<?php
// READ-ONLY: catalog model
public function getEngine(): \Acme\Badge\Engine {
    $version = (int)$this->config->get('module_acme_badge_version');
    $key = 'acme_badge.rules.v' . $version;

    $rules = $this->cache->get($key);
    if (!$rules) {
        $query = $this->db->query("SELECT * FROM `" . DB_PREFIX . "acme_badge_rule` WHERE `status` = '1' ORDER BY `priority`");
        $rules = $query->rows;
        $this->cache->set($key, $rules);
    }

    return new \Acme\Badge\Engine($this->normalise($rules), new \DateTimeImmutable('today'), (int)$this->config->get('module_acme_badge_max'));
}

Because the schedule dates are checked by the engine against "today", the cache never needs to be cleared when a promotion starts or ends.

PHP A versioned cache key and a query counter

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.

Step 5: test and ship

  • Test the engine the way the shipping project tests its rate engine: boundaries (stock exactly at the threshold, a rule ending today), duplicates and the maximum-badge limit.
  • Test the integration on a development store with the default theme and with a custom one, and with the event disabled in the admin to be sure the page still works.
  • Check performance by counting queries on a 100-product category page with the extension on and off: the difference should be about two queries.
  • Package it with the steps in Packaging, Marketplace and Upgrades.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why does the extension preload product data in an event on the product list instead of querying inside the card event?

    Card events fire once for each product. A query there would be an N+1 problem. Loading data for all products once per page keeps the card handler free of queries.
  2. 2. A scheduled rule has end date 2025-06-30. What happens on July 1st?

    The engine checks the schedule against the current date on every call, so a rule ends by itself and no cache has to be cleared.
  3. 3. What does the insertion helper do when the card HTML has no known marker?

    Themes differ. Leaving the card untouched means the worst case is missing badges, not a broken page.
  4. 4. How does a versioned cache key avoid stale rules after an admin edit?

    A new version produces a new key that has no cached value yet, so fresh rules are loaded, while the old entry simply expires unused.

Summary

  • Keep the decision logic in a pure rule engine that takes a product, rules and a date.
  • Store rules in an indexed table with a type, value, priority, schedule and status.
  • Use a list event to preload data for the whole page and a card event to add badges, so there is no query per card.
  • Insert markup defensively: escape labels, look for one marker, and do nothing when it is absent.
  • Cache the rules under a versioned key and compute badges on the fly, so stock and dates are never stale.
  • Test the engine's edges and the integration with different themes.

Next: Project: Order Webhook Exporter