Events in OpenCartA free open-source CMS for online stores, written in PHP with a MySQL/MariaDB database. Everything that is not part of the core is added through extensions. More in the glossary → are a mechanism that lets you run your code before or after a controllerCode that receives a request and prepares data. More in the glossary →, model, template, or language fileA PHP file with interface texts, separate for each language. More in the glossary → is called, without changing core files. You register a trigger such as catalog/ and an action (a method of your controller), and the OpenCart loader calls it at the right moment. Below is how this works in the 3.0 and 4.1 code, and where the versions behave differently.
Examples are for OpenCart 4.1; in 4.0.x, model triggers and event handling differ.
What is an event in OpenCart and what does it consist of?
The whole event system is one small Event class in the system/ file. It stores an array of "trigger → action → priority" records and has four methods: register(), trigger(), unregister(), and clear(). The event object is held in the registry under the key event, so any controller can access it as $this->event (how objects get into the registry is described in the article about the Registry and shared objects in OpenCart).
Each event has three components:
- Trigger — a string that describes the moment of the call: the object type, its route, and the phase. For example,
model/in 3.0.catalog/ product/ getProduct/ after - Action — the controller route to execute. In 3.0 this is the
Actionobject, in 4.1 it is\Opencart\System\Engine\Action. - Priority — an integer. After each registration, the array is sorted via
array_multisort(..., SORT_ASC, ...), so the handler with the lower number runs first.
Events don't "listen" for anything on their own. They are explicitly fired by the core loader: when you write $this or call a model method, Loader first runs trigger('…/, then performs the work, and then trigger('…/. That is why events exist only where code goes through the loader. A direct new SomeClass() or an SQL query that bypasses the model triggers no events. For more on the call path, see the article about Loader and the load->controller, model, view methods.
How does the core match a trigger to an event?
The key piece is the trigger() method. It iterates over the registered records and compares each trigger with the event name using a regular expression.
system/ · OpenCart 3.0.5.1 · lines 59–69
public function trigger($event, array $args = array()) {
foreach ($this->data as $value) {
if (preg_match('/^' . str_replace(array('\*', '\?'), array('.*', '.'), preg_quote($value['trigger'], '/')) . '/', $event)) {
$result = $value['action']->execute($this->registry, $args);
if (!is_null($result) && !($result instanceof Exception)) {
return $result;
}
}
}
}
- The asterisk
*means any sequence of characters, the question mark?means one character. The rest is escaped viapreg_quote(), so the dot in a 4.1 trigger is a literal dot, not "anything". - The expression is anchored only to the start of the string (
^), there is no end anchor. A triggerview/common/headerwithout a phase will fire on bothview/andcommon/ header/ before /after. Always specify the phase explicitly. - Errors in a trigger are silent. If the string doesn't match, the handler is simply not called, and nothing is written to the log.
The event names the loader generates look like {тип}/: controller/…, model/…, view/…, language/…, config/…. In 4.1, library/…/before are added to them. There is no catalog/ or admin/ prefix in the event name: it is stripped by the startup/event controller when it reads events from the database (more on this below).
Where do the registered events come from?
There are two sources, and it is worth distinguishing between them when you are looking for why something fires.
The action_event config
The system/ and system/ files contain an $_['action_event'] array. At startup, system/ registers each of its elements, and the array key becomes the priority. This is how the core attaches its own service handlers: in 3.0 these include, among others, event/theme and event/language on view/*/before; in 4.1, also event/, event/, and event/. These files belong to the core, and modules do not edit them.
The event table
Modules register events in the oc_event table (the prefix depends on the installation). On every request, the startup/event controller reads it through the setting/event model and calls register() for each row.
catalog/ · OpenCart 4.1.0.4 · lines 18–32
$results = $this->model_setting_event->getEvents();
foreach ($results as $result) {
$part = explode('/', $result['trigger']);
if ($part[0] == 'catalog') {
array_shift($part);
$this->event->register(implode('/', $part), new \Opencart\System\Engine\Action($result['action']), $result['sort_order']);
}
if ($part[0] == 'system') {
$this->event->register($result['trigger'], new \Opencart\System\Engine\Action($result['action']), $result['sort_order']);
}
}
OpenCart 3.0: the storefrontWhat the customer sees: the home page, categories, product page, and cart. More in the glossary → loads from the database only rows with trigger LIKE 'catalog/ and status = '1'; the admin loads rows with the admin/ prefix and an enabled status. The prefix is stripped, and the rest goes into register().
OpenCart 4.1: the storefront model selects all enabled events, and the controller itself parses the prefix. In addition to catalog/ and admin/, the system/ prefix was added: a trigger with this prefix is registered without changes in both applications.
The list of events recorded in the database can be viewed in the admin: ExtensionsAdditional functionality: a module, a payment or shipping method, a feed, or a theme. They are managed in "Extensions → Extensions." More in the glossary → → Events, route marketplace/event. Here you can enable, disable, or delete an event. This is the fastest way to check whether a module's event is causing a problem, without removing the module itself.

The standard page shows only the list of rows: it does not show whether an event is working or how much time its handler takes. For OpenCart 3 there is a free module, OCT Event Manager — event manager for OpenCart 3, which works without OCMOD. It shows all the store's events, finds broken and slow ones, and helps disable third-party events. This can be done even when the admin no longer opens after a module is installed, without manually editing the event table in the database.
How do you write a trigger correctly in 3.0 and 4.1?
The most common cause of "the event doesn't work" is the wrong separator between the route and the method. Here is how the same things look in both branches:
| What | OpenCart 3.0 | OpenCart 4.1 |
|---|---|---|
| Trigger for a model method | catalog/ | catalog/ |
| Trigger for a template | catalog/ | catalog/ |
| Action (handler) | extension/ | extension/ |
| Add an event | addEvent($code, $trigger, $action, $status = 1, $sort_order = 0) | addEvent(array $data): int with keys code, description, trigger, action, status, sort_order |
| Table columns | code varchar(64), no description | code varchar(128), has description |
Note: in 4.1 the model method is separated by a dot, because the loader builds the route as $route . '.' . $method. A trigger catalog/ in 4.1 will never match. The same applies to the action: the Action class in 4.1 looks for the method after the last dot, and without it calls index. The 4.1 core records its own events exactly this way: catalog/ with the action event/.
The method name has also changed: in 3.0 the order history is added by addOrderHistory(), in 4.1 by addHistory(). Before you register a trigger on a model, open the model file for the relevant version and copy the method name from there.
Event registration usually happens in the install() method of the module's controller, and removal in uninstall() via deleteEventByCode(). The execution order and registration practices are covered separately, and the general installation scheme is in the article about module install and uninstall.
What does the handler receive and what can it change?
The handler is a regular public controller method. Arguments are passed by reference, so changing them changes what the core will work with. The set of arguments depends on the event type:
| Event | OpenCart 3.0 | OpenCart 4.1 |
|---|---|---|
controller/*/before | &$route, &$data | &$route, &$args |
controller/*/after | &$route, &$data, &$output | &$route, &$args, &$output |
model/*/before | &$route, &$args | &$route, &$args |
model/*/after | &$route, &$args, &$output | &$route, &$args, &$output |
view/*/before | &$route, &$data, &$code | &$route, &$data, &$code, &$output |
view/*/after | &$route, &$data, &$output | &$route, &$data, &$output |
language/*/before | &$route, &$key | &$route, &$prefix, &$code |
library/*/before | none | &$route, &$args |
The table describes calls made via Loader. The exception is the 3.0 admin main controller: admin/ passes only &$route, &$output to the after event.
Typical techniques: in view/*/before, add a variable to $data or replace $route with your own template; in model/*/after, extend the $output array; in model/*/before, change the call arguments via $args. Separately, there are articles in the section on templates and models: "Changing a template via the view/*/before event" and "Intercepting models: model/*/after".
A minimal handler for 4.1 that adds a variable to the product card template:
public function productView(string &$route, array &$data, string &$code, string &$output): void {
$data['my_badge'] = $this->config->get('module_my_module_badge');
}
In 3.0 the same handler is written without types: public function productView(&$route, &$data, &$code). The my_badge variable is then available in Twig as {{ my_badge }} (see variables and filters in Twig in OpenCart).
How does returning a value differ between 3.0 and 4.1?
This is the main difference between the branches, and it breaks modules ported from 3.0 without checking.
OpenCart 3.0: Event::trigger() returns the first result that is neither null nor Exception, and immediately stops the iteration. Other handlers of the same event with a higher priority will no longer run. The loader uses this result as follows:
system/ · OpenCart 3.0.5.1 · lines 40–56
// Trigger the pre events
$result = $this->registry->get('event')->trigger('controller/' . $trigger . '/before', array(&$route, &$data));
// Make sure its only the last event that returns an output if required.
if ($result != null && !$result instanceof Exception) {
$output = $result;
} else {
$action = new Action($route);
$output = $action->execute($this->registry, array(&$data));
}
// Trigger the post events
$result = $this->registry->get('event')->trigger('controller/' . $trigger . '/after', array(&$route, &$data, &$output));
if ($result && !$result instanceof Exception) {
$output = $result;
}
So in 3.0, return from a before handler cancels the call of the controller, model, or template itself, and return from an after handler replaces the result. Hence the classic mistake: a handler accidentally returns true or a string, and the page or model method "disappears".
OpenCart 4.1: trigger() runs all handlers, ignores their values, and returns an empty string.
system/ · OpenCart 4.1.0.4 · lines 69–77
public function trigger(string $event, array $args = []) {
foreach ($this->data as $value) {
if (preg_match('/^' . str_replace(['\*', '\?'], ['.*', '.'], preg_quote($value['trigger'], '/')) . '/', $event)) {
$value['action']->execute($this->registry, $args);
}
}
return '';
}
The result can be changed only through arguments passed by reference. For templates there is a separate mechanism: view/*/before receives &$output, and if a handler fills it, rendering is skipped. For models there is no such bypass: in 4.1, a model's before event can change $args, but the model method will still be called.
What does the full call cycle with events look like?
The diagram for a template in 4.1 (for controllers and models the logic is the same, just without the rendering bypass):
flowchart TD
A["load->view(route, data)"] --> B["trigger view/route/before"]
B --> C{"output filled?"}
C -- "yes" --> E["trigger view/route/after"]
C -- "no" --> D["template->render(route, data, code)"]
D --> E
E --> F["return output"]
The main controller of the page (the one defined by the route parameter) is also wrapped with controller/ and /after events: in 3.0 this is done by startup/router, in 4.1 directly by system/. How the core finds this controller is described in the articles about the request path in framework.php and routing with route= in 3.0 and 4.1.
Things to keep in mind when debugging:
- Priority is ascending:
sort_order0 runs before 10. In 4.1 the default value in the table is 1, in 3.0 it is 0. - In 3.0, the core's service handlers on
view/*/beforehave priorities such as 500 and 998 (storefront), so a module handler with a lower number runs before them. - An event disabled in the admin is not registered at all: both branches filter by
status. - Events do not fully replace modifications. If you need to insert code inside a core method, in 3.0 OCMOD is used for this: an
install.xmlfile in the archive and the "Refresh" button (see the blog: OCMOD in OpenCart: code edits without changing system files). In 4.1 there is also Extensions → Modifications (routemarketplace/) andmodification ocmod/*.ocmod.xmlfiles in the archive, but for new code it is better to use events.
Summary
- The event system is the
Eventclass insystem/;engine/ event.php Loaderfires events before and after controllers, models, templates, language files, and configs, and in 4.1 also libraries. - Events come from the
action_eventconfig (core) and from theeventtable (modules), which can be viewed in Extensions → Events. - A trigger is matched by a regular expression anchored at the start of the string;
*and?work as wildcards, and an error in a trigger gives no message at all. - In 4.1 the model method and action are separated by a dot; in 3.0, by a slash.
- In 3.0 the value returned by a handler cancels the call or replaces the result and stops other handlers; in 4.1 the value is ignored, and only arguments passed by reference take effect.
Next, it is worth looking at how a module registers events and manages their order, and how to change templates and models through events. All the materials are gathered in the section Events and OCMOD; the basic structure of a module is described in the article anatomy of an OpenCart extension.