No results found

Try a different search query

Popular searches:

Add to Cart

Cart

You have no purchases yet

Browse Marketplace
Original Subtotal:
Product discounts:
Quantity Discount:
Total:
View Cart
Events and OCMOD

Event model in OpenCart: intercepting models via model/*/after in 3.0 and 4.1

How to use the model/*/after event to change the data an OpenCart model returns to the controller, and react to a database write. Why the event sometimes doesn't fire and where the limits of the hook lie.

9 min read OC 3.0 OC 4.1

An model event in OpenCart is an event that the core triggers before and after each public method of a model loaded through $this->load->model(). In the model/…/after handler, you get the call arguments and the method's result by reference, so you can add product data, filter a list, or react to order creation without changing model files. The key is to write the trigger correctly and know when the event won't fire at all.

Examples are for OpenCart 4.1; in 4.0.x, model triggers and event handling differ. For the general event mechanics, see the article OpenCart event system, and for registering events in a module, see addEvent and handler order.

How does the core wrap a model in events?

When a controller calls $this->load->model('catalog/product'), the loader does not put the model object itself into the registry. It creates a proxy object and, for each class method, writes a closure. During a call to $this->model_catalog_product->getProduct(42), that closure performs three steps:

  1. it triggers the event model/catalog/product…getProduct/before with the arguments &$route, &$args;
  2. it runs the actual model method with the array $args;
  3. it triggers the event model/…/after with the arguments &$route, &$args, &$output, where $output is what the method returned.

The trigger format depends on the version, and this is the most common reason an event "stays silent":

WhatOpenCart 3.0OpenCart 4.1
Trigger for the product cardcatalog/model/catalog/product/getProduct/aftercatalog/model/catalog/product.getProduct/after
Trigger for saving a product in adminadmin/model/catalog/product/editProduct/afteradmin/model/catalog/product.editProduct/after
Handler signature(&$route, &$args, &$output)(string &$route, array &$args, &$output): void
Product not foundgetProduct() returns falsegetProduct() returns []

In 3.0, there is a slash between the model route and the method; in 4.1, it is a dot. A trigger with the wrong separator simply won't match, and you won't see any error.

$args is the array of arguments in the method's signature order: for getProduct($product_id) it is $args[0], and for editProduct($product_id, $data) it is $args[0] and $args[1]. Take the types of $output from the model method of the required version itself, because they differ (false versus [] in the table above). For the structure of models, see the article OpenCart model and $this->db.

How do you add product data in getProduct/after?

A typical task is to show an extra field from the module's table on the product card, or to change the name for a certain customer groupA segment of buyers (retail, wholesale) with different prices and terms. More in the glossary →. The handler receives the product array in $output and modifies it in place.

Example

// OpenCart 4.1, тригер catalog/model/catalog/product.getProduct/after
public function productAfter(string &$route, array &$args, &$output): void {
	if (!$output || !$this->config->get('module_my_module_status')) {
		return;
	}

	$this->load->model('extension/my_module/module/my_module');

	$output['my_label'] = $this->model_extension_my_module_module_my_module->getLabel((int)$args[0]);
}

// OpenCart 3.0, тригер catalog/model/catalog/product/getProduct/after
public function productAfter(&$route, &$args, &$output) {
	if (!$output || !$this->config->get('module_my_module_status')) {
		return;
	}

	$this->load->model('extension/module/my_module');

	$output['my_label'] = $this->model_extension_module_my_module->getLabel((int)$args[0]);
}

The check for !$output at the start covers both "product not found" cases: false in 3.0 and [] in 4.1. Without it, the handler would write a key into an empty result, and the product card controller would treat a nonexistent product as found.

A new field in the product array does not mean it will appear on the page: the product/product controller passes to the template only the keys it knows about. To show my_label, add it to the template data with the view/product/product/before event. This technique is described in the article changing templates via view/*/before.

Why doesn't a model event sometimes fire?

The event occurs only when the method is called through the proxy, that is, as $this->model_…->метод(). Anything that bypasses the proxy generates no events. Here are the situations where developers most often lose time:

  • Calling a method from within the same model. Inside the model class, $this is the object itself, not the proxy. In 3.0, getProducts(), getLatestProducts(), getPopularProducts(), getBestSellerProducts(), and getProductRelated() build their results through calls to $this->getProduct(). So a handler on getProduct/after will change the product card, but not the category and module lists.
  • Libraries with direct SQL queries. The cart (system/library/cart/cart.php) in both branches reads products, prices, and discounts directly from the database, without the catalog model. A price changed in getProduct/after will appear on the product card, but not in the cart or in the order.
  • Wrong application. The catalog/… trigger fires only on the storefrontWhat the customer sees: the home page, categories, product page, and cart. More in the glossary →, and admin/… only in admin. The catalog/product model exists in both, but these are different files with different methods.
  • A different method name in the version. In 3.0, order history is added by addOrderHistory(); in 4.1, by addHistory(). Related productsProducts shown on a product page as recommendations. They increase the average order value. More in the glossary → are returned by getProductRelated() in 3.0 and getRelated() in 4.1.

This leads to a practical rule: intercept the method that the controller calls, not the one that sits deeper. For a category list, that is getProducts.

What needs to changeOpenCart 3.0OpenCart 4.1
Product cardgetProductgetProduct
Category list, searchgetProducts (array with keys product_id)getProducts (array of query strings)
Related productsgetProductRelatedgetRelated

In 4.1, getProducts() itself gets all columns in one query and caches rows by the SQL hash. The after event fires after the data is read from the cache, so your changes do not get into the cache and are applied on every call.

How do you react to database writes: orders and products?

The second common task is to do something after the core has written the data: send an order to a CRM, update stock levels, or clear your module's own cache. After-events of the add*, edit*, and delete* methods are suitable for this.

Example

// OpenCart 4.1, тригер admin/model/catalog/product.editProduct/after
public function productSaved(string &$route, array &$args, &$output): void {
	$product_id = (int)$args[0];
	$data = $args[1];

	// $data містить усі поля форми: model, sku, price, product_description тощо
	$this->cache->delete('my_module.product.' . $product_id);
}

It is useful to know what the write methods return. addOrder() on the storefront returns the new order id in both branches, so in addOrder/after it is in $output. editProduct() in 4.1 returns nothing (void), so take the product id from $args[0].

For order statusA stage of processing: "Pending," "Shipped," "Complete." Custom statuses are added in the dictionary. More in the glossary → changes, the most reliable hook is catalog/model/checkout/order/addOrderHistory/after in 3.0 and catalog/model/checkout/order.addHistory/after in 4.1. Status changes from payment modules pass through this method, so the core itself attaches its internal order statistics handler to it (on after in 3.0, on before in 4.1). $args[0] holds the order id, and $args[1] holds the new status id.

Extensions → Events: model triggers with a dot before the method in 4.1
Extensions → Events: model triggers with a dot before the method in 4.1 · OpenCart 4.1.0.4

While processing, keep response time in mind: the handler runs synchronously in the same request. Calling an external API from addHistory/after will delay the response to the payment service or the customer for the duration of that call. For heavy operations, write the task to your own table and process it separately (see the article on background tasks in OpenCart modules).

What can you do in model/*/before?

The before event receives &$route and &$args before the method is called. Changing the arguments is most useful here: for example, adding a filter to the $args[0] array before getProducts, or correcting form data before editProduct.

Example

// OpenCart 4.1, тригер catalog/model/catalog/product.getProducts/before
public function productsBefore(string &$route, array &$args): void {
	if (isset($args[0]['limit']) && (int)$args[0]['limit'] > 100) {
		$args[0]['limit'] = 100;
	}
}

Here the versions differ fundamentally:

  • OpenCart 3.0: if the before handler returns a value that PHP considers true, the real method will not run, and this value becomes the result. This way, you can, for example, return data from your own cache.
  • OpenCart 4.1: it is impossible to cancel a model call. The loader always runs the method after the before event, and the handler's return value is ignored. You can only change $args, and the result is changed in the after event.

Therefore, logic that "fully replaces the result," carried over from 3.0, is rewritten in 4.1 as an after handler that overwrites $output. The model method will still execute its query in that case.

flowchart TD
A["controller: model_catalog_product->getProducts(data)"] --> B["proxy: trigger model/…/before"]
B --> C{"3.0: did the handler return a value?"}
C -- "yes" --> E["trigger model/…/after"]
C -- "no, or 4.1" --> D["run the model method"]
D --> E
E --> F["return output to the controller"]

What are the limits of intercepting models?

Model events are a powerful tool, but not a universal one. Before building a module feature on them, check three things.

  • Whether the needed data passes through the model at all. Cart prices, order totalsLines at the bottom: total, shipping, discount, coupon. Managed in "Extensions → Extensions": in the list of types, select "Order Totals." More in the glossary →, and part of the shipping calculations come from libraries or from total modules. It is better to apply a discount the customer actually pays through a total-type module than through an event on getProduct. For extension types, see the article OpenCart module types.
  • How many times the handler will run. An event on getProduct in 3.0 doesn't affect lists, but other modules may call getProduct through the proxy in a loop. Don't run a separate SQL query per product in the handler if you can fetch the data for the whole list in one query.
  • Whether you conflict with another module. Several modules often hook the same methods. In 3.0, a handler that returns a value stops the others; in 4.1, all handlers run in sequence and see the changes made by previous ones. An explicit sort_order makes the result predictable.

If you need to change the logic inside a core method (an SQL condition, the order of calculations) rather than its input or output, events won't help. In 3.0, OCMOD remains the option for this (install.xml in the archive, "Refresh" button). In 4.1, there is also the Extensions → Modifications page and ocmod/*.ocmod.xml files in the archive, but for new code it is better to use events. Articles in this section cover which approach to choose for your case.

Summary

  • A model event occurs only for calls made through the $this->model_…->метод() proxy; internal $this->метод() calls and direct library queries trigger no events.
  • Trigger: …/product/getProduct/after in 3.0, …/product.getProduct/after in 4.1; the handler receives &$route, &$args, &$output.
  • Check for an empty result: false in 3.0 and [] in 4.1.
  • For lists, intercept getProducts; for order status, intercept addOrderHistory (3.0) or addHistory (4.1).
  • In 3.0, a before handler can cancel the call; in 4.1, it can only change $args.

The full list of articles on events and modifications is collected in the section Events and OCMOD.

FAQ

Can you intercept a method of your module's own model?
Yes. If the model is loaded via $this->load->model(), its methods are wrapped in a proxy just like core models. The trigger is built from the model's route, for example catalog/model/extension/my_module/module/my_module.getLabel/after in 4.1.
Will a model event fire when it is called from another event handler?
Yes, the handler calls the model through the proxy, so events will fire for it too. Make sure the handler does not call the same method the event is attached to, or you will get infinite recursion.
How do you see which model methods are called on a page?
Temporarily register a handler on catalog/model/*/after that writes $route to the log via $this->log->write(). After checking, be sure to delete the event, because it fires on every model call.
Was this article helpful?
Thanks for your feedback!

Related articles

Didn't find the answer?

Ask the community: OpenCart developers answer on the forum.

Ask on the forum
We use cookies

We use cookies and similar technologies to improve your experience, analyse traffic, and show personalised ads. Read our Cookie Policy for details.