# OpenCart Event System: before/after, Triggers and Handlers in 3.0 and 4.1

> How Events Work in OpenCart 3.0 and 4.1: Where Triggers Come From, How the Core Matches Them, What before and after Handlers Can Do, and Where the Versions Differ.

Джерело: https://opencartcode.com/en/wiki/dev-events-ocmod/events-opencart
OpenCart: 3.0, 4.1
Оновлено: 2026-11-28

Events in [OpenCart](https://opencartcode.com/en/wiki/glossary/e-commerce-glossary#opencart) are a mechanism that lets you run your code before or after a [controller](https://opencartcode.com/en/wiki/glossary/e-commerce-glossary#controller), model, template, or [language file](https://opencartcode.com/en/wiki/glossary/e-commerce-glossary#language-file) is called, without changing core files. You register a trigger such as `catalog/view/product/product/before` 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/engine/event.php` 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](https://opencartcode.com/en/wiki/dev-architecture/registry-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/catalog/product/getProduct/after` in 3.0.
- **Action** — the controller route to execute. In 3.0 this is the `Action` object, 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->load->view()` or call a model method, `Loader` first runs `trigger('…/before')`, then performs the work, and then `trigger('…/after')`. 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](https://opencartcode.com/en/wiki/dev-architecture/opencart-loader).

## 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/engine/event.php` · OpenCart 3.0.5.1 · lines 59–69

```php
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;
			}
		}
	}
}
```

1. **The asterisk `*` means any sequence of characters, the question mark `?` means one character.** The rest is escaped via `preg_quote()`, so the dot in a 4.1 trigger is a literal dot, not "anything".
2. **The expression is anchored only to the start of the string (`^`), there is no end anchor.** A trigger `view/common/header` without a phase will fire on both `view/common/header/before` and `/after`. Always specify the phase explicitly.
3. **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/config/catalog.php` and `system/config/admin.php` files contain an `$_['action_event']` array. At startup, `system/framework.php` 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/modification.controller`, `event/modification.model`, and `event/modification.library`. 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/controller/startup/event.php` · OpenCart 4.1.0.4 · lines 18–32

```php
$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 [storefront](https://opencartcode.com/en/wiki/glossary/e-commerce-glossary#storefront) 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: [Extensions](https://opencartcode.com/en/wiki/glossary/e-commerce-glossary#extensions) → 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.

Extensions → Events: event code, trigger, action, and status · OpenCart 4.1.0.4

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](https://opencartcode.com/en/marketplace/product/oct-event-manager), 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/model/checkout/order/addOrderHistory/after` | `catalog/model/checkout/order.addHistory/after` |
| Trigger for a template | `catalog/view/product/product/before` | `catalog/view/product/product/before` |
| Action (handler) | `extension/module/my_module/orderHistory` | `extension/my_module/module/my_module.orderHistory` |
| 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/model/checkout/order/addHistory/after` 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/model/account/customer.addCustomer/after` with the action `event/activity.addCustomer`.

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](https://opencartcode.com/en/wiki/dev-extensions/install-opencart-module).

## 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/controller/startup/router.php` 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:

```php
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](https://opencartcode.com/en/wiki/dev-mvc/opencart-twig-templates)).

## 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/engine/loader.php` · OpenCart 3.0.5.1 · lines 40–56

```php
// 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/engine/event.php` · OpenCart 4.1.0.4 · lines 69–77

```php
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.

> When porting a module from 3.0 to 4.1, look through the handlers for all `return` with a value. In 4.1 they do nothing: replace them with an assignment to `$output = …` in after events, or by filling `$output` in `view/*/before`.

## 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):

```mermaid
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/…/before` and `/after` events: in 3.0 this is done by `startup/router`, in 4.1 directly by `system/framework.php`. How the core finds this controller is described in the articles about the [request path in framework.php](https://opencartcode.com/en/wiki/dev-architecture/opencart-framework-php) and [routing with route= in 3.0 and 4.1](https://opencartcode.com/en/wiki/dev-mvc/opencart-route).

Things to keep in mind when debugging:

- Priority is ascending: `sort_order` 0 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/*/before` have 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.xml` file in the archive and the "Refresh" button (see the blog: [OCMOD in OpenCart: code edits without changing system files](https://opencartcode.com/en/blog/ocmod-v-opencart-pravki-kodu-bez-zmini-sistemnix-failiv)). In 4.1 there is also Extensions → Modifications (route `marketplace/modification`) and `ocmod/*.ocmod.xml` files in the archive, but for new code it is better to use events.

## Summary

- The event system is the `Event` class in `system/engine/event.php`; `Loader` fires events before and after controllers, models, templates, language files, and configs, and in 4.1 also libraries.
- Events come from the `action_event` config (core) and from the `event` table (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](https://opencartcode.com/en/wiki/dev-events-ocmod); the basic structure of a module is described in the article [anatomy of an OpenCart extension](https://opencartcode.com/en/wiki/dev-extensions/opencart-module-structure).

## FAQ

**Can I register an event without writing to the database?**

Yes, by calling $this->event->register() directly in code, but such a registration is only active until the end of the current request. For a module, it is more reliable to write the event to the event table during installation.

**How do I see which events fired on a page?**

The simplest way is to temporarily write to the log from a handler using $this->log->write(). In 4.1, system/config/catalog.php has commented-out event/debug handlers that show how this is done in the core.

**Will a module's event still fire if the module is disabled in its settings?**

Yes, as long as the event remains enabled under "Extensions → Events". The module status and the event status are independent, so check the module's settings inside the handler.

**What happens to events when a module is deleted?**

The core does not remove them automatically by module name: this must be done by the uninstall() method via deleteEventByCode(). If this is not done, the event will remain and point to a missing controller.
