Skip to content
Tutorials Center
My learning

Topics

Lesson 9 of 27 ยท Events and OCMOD

Events

Learn how OpenCart 4 events let an extension change views, controllers and models without editing core files: triggers, actions, arguments by reference, priority.

A store owner installs your extension and wants a "Free shipping over 50" banner on every product page. Your first thought might be to open the product template and paste the banner in. That works until the next OpenCart update overwrites the file, or until another extension edits the same line. OpenCart's answer is events: small hooks that run before or after a piece of core code, registered in the database, so you can change what the core does without touching a single core file.

In this lesson you will learn how an event is stored, what a trigger looks like, how your handler receives its arguments by reference, how priority works, and how to find out why a handler is not running. The OpenCart code is shown read-only, because it needs a running store; the runnable examples are stand-in dispatchers written in plain PHP that follow the same rules. If you have used Magento observers, see Events and Observers for the comparison. Events are the main tool for extending OpenCart 4, and OCMOD Modifications is the fallback when no event exists.

What an event is

An event is one row in the event table:

Column Meaning
code A unique name you choose, for example acme_free_shipping_banner
description Free text shown in the admin
trigger Which core action to hook, such as catalog/view/product/info/after
action The route of your handler, such as extension/acme/event/banner
status 1 enabled, 0 disabled
sort_order Lower numbers run first

At the start of each request, a startup step reads the enabled rows and registers each handler under its trigger pattern. Whenever the core reaches a place that can be hooked, it asks the event system whether any registered pattern matches and calls those handlers in order. You create the row in your extension's install() method (see Install, Uninstall and Permissions) and delete it by code in uninstall().

Trigger names

A trigger is a path made of three parts: where the code runs (catalog or admin), what kind of thing it is, and whether your handler runs before or after.

Kind Example trigger Fires
View catalog/view/product/info/before Before the Twig template product/info is rendered
View catalog/view/product/info/after After it is rendered, with the HTML available
Controller catalog/controller/checkout/cart.add/before Before that controller method runs
Model catalog/model/checkout/order/addOrder/after After the model method returned
Language catalog/language/product/info/after After a language file is loaded

You can use * as a wildcard, for example catalog/view/*/after to see every rendered view. Wildcards are powerful and costly: your handler runs for every match. Prefer the most specific trigger you can.

The names inside the trigger come from the route or template path the core uses, so they differ between versions and between core and extension templates. Always read the loader code or search the core for the route to find the exact string in your version. The method separator in a controller trigger (cart.add here, cart|add in the earliest 4.0 releases) also depends on the version.

Writing a handler

A handler is a normal controller class placed in the event folder of your extension. This one adds a banner to the product page. It is read-only, because it needs a running store.

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

class Banner extends \Opencart\System\Engine\Controller {
    public function index(string &$route, array &$data, mixed &$output): void {
        $threshold = (float)$this->config->get('module_acme_banner_threshold');

        if ($threshold > 0) {
            $banner = '<div class="alert alert-info">Free shipping over '
                . $this->currency->format($threshold, $this->session->data['currency'])
                . '</div>';

            $output = $banner . $output;
        }
    }
}

The three parameters are references (&). That is the whole trick. What you assign to them changes what the core uses next:

  • In a before view event, the arguments are the route and the $data array the controller prepared. Changing $data['heading_title'] changes what the template prints. This is the safest kind of change, because the template still renders itself.
  • In an after view event, $output is the final HTML string. You can prepend, append or replace parts of it. This is blunt, so use it for small insertions and avoid rewriting large parts with string functions.
  • In a before controller event, you can alter the arguments passed to the method.
  • In an after controller or model event, $output holds the result, which you can alter before it is used.

Because the parameters are references, the signature must say &, and the handler must keep the parameter order the core expects. If you drop the &, your changes silently go nowhere.

sequenceDiagram
    participant C as Core controller
    participant E as Event system
    participant H as Your handler
    participant T as Twig
    C->>E: trigger view/product/info/before (route, data)
    E->>H: index(&route, &data)
    H-->>E: data changed in place
    C->>T: render with the changed data
    T-->>C: HTML
    C->>E: trigger view/product/info/after (route, data, output)
    E->>H: index(&route, &data, &output)
    H-->>E: output changed in place
    C-->>C: send output

Before and after hooks surround one core step. Because arguments are references, edits made by a handler are visible to the core.

Adding data to a view

Often you need a new variable in a template, not just an HTML snippet. The clean pattern uses two events together. A before-view handler adds your data to $data; the theme template then prints it. For templates you do not own, the after-view handler is the only option, because you cannot add a Twig variable the template never mentions. Many extensions therefore combine a before-view handler to compute and an after-view handler to place the result. Where a module can be placed in a layout position instead, a module is cleaner than an event (see Modules and Layouts).

Priority and conflicts

Several extensions can hook the same trigger. Handlers run in ascending sort_order, and with equal numbers the order is not something to rely on. Each handler sees the output of the previous one, so two extensions that both rewrite $output can interfere. Good habits:

  • Make small, targeted changes. Insert at a clearly identified spot, or add to $data, instead of replacing everything.
  • Check that what you expect to be in $output is really there before you change it. Another handler may have changed it first.
  • Do not return values from handlers to control flow unless you know your version uses them; in some places a non-empty return value from a before event makes the core skip the original action, which is a very strong effect.
  • Keep handlers fast. A wildcard trigger may run dozens of times per page.

Debugging events

When a handler does not run, check in this order:

  1. Is the row there and enabled? Look at the event table (the admin has an Events page under Design or System, depending on the version). Wrong status or a missing row after a failed install is common.
  2. Does the trigger match? A single character off, a different method separator, or the wrong area prefix (admin instead of catalog) means the pattern never matches. Log the route the core actually uses.
  3. Does the action route resolve? The action must point at a real file and method, with the right namespace and capitalization. A typo produces an error in the error log or silently nothing.
  4. Is the response cached or served by a different template? Theme overrides and view caches can hide your change.
  5. Is another handler overwriting yours? Lower your sort_order number, or raise it, and watch the effect.

Write a line to the log to confirm the handler is reached: $this->log->write('banner event: ' . $route);. The error log is in the storage logs folder, and Testing and Debugging Extensions covers it in detail.

Try it: a before/after dispatcher

This stand-in is not OpenCart's event class. It follows the same shape: handlers registered under trigger patterns, a before hook that edits the data, and an after hook that edits the output, both through references.

PHP Before and after hooks around a render

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 product page is changed by both hooks, while the category page, whose route does not match, is rendered unchanged. Remove the & from one of the handler parameters and run it again to see that its changes disappear.

The second example shows wildcard triggers and sort_order. Handlers run in ascending order, and a later handler sees what the earlier ones did.

PHP Wildcards, sort order and a debug trace

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 badge handler (sort 10) runs first and the wrapper (sort 20) wraps the already-changed text. The disabled old_hook shows up in the trace as skipped, which is the kind of line you want when you debug a missing event on a real store.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why do event handler parameters like $data and $output carry an ampersand?

    They are passed by reference. Without the ampersand, the handler would edit a copy and the core would never see the change.
  2. 2. Which trigger runs after the product info template is rendered, with the HTML available?

    View triggers end in before or after. The after variant receives the rendered output, and the catalog prefix selects the storefront.
  3. 3. Two extensions hook the same trigger. What decides who runs first?

    Handlers run in ascending sort_order. A later handler sees the changes of the earlier one, so keep your edits small.
  4. 4. Your handler never runs. Which check comes first?

    Missing or disabled rows and mistyped triggers are the most common causes, so check the event table before anything else.

Summary

  • An event is a database row linking a trigger (such as catalog/view/product/info/after) to an action route, with a status and a sort order.
  • Register events in install() and delete them by code in uninstall().
  • Handlers receive arguments by reference; before-hooks change inputs, after-hooks change outputs.
  • Prefer specific triggers over wildcards, keep handlers fast, and make small edits so extensions do not clash.
  • Handlers run in ascending sort_order; later ones see earlier changes.
  • When an event does nothing, check the row, the trigger string, the action route and other handlers, in that order.

Next, learn the fallback for places that have no event in OCMOD Modifications.