How to use Opencart Events
In Opencart 4, the Event System is a powerful feature that allows developers to execute specific actions at predefined points in the code execution process. This mechanism is particularly beneficial for extending the platform’s functionality without altering its core files, thereby maintaining the integrity and upgradability of the OpenCart system.
When a certain event occurs, the event system calls all registered handlers for that event. Each handler can have its own code to handle its event.
How Opencart Events Work
When an event is triggered, the system automatically calls all registered handlers associated with that event. Each handler can contain custom code to perform the desired actions, such as sending emails, updating records, or integrating with third-party services.
Event Types
1. Pre-Events:
Triggered before a specific action occurs. For example, a pre-event can be triggered before an order is saved, allowing developers to perform custom actions like validating order data.
2. Post-Events:
Triggered after a specific action occurs. For example, a post-event can be triggered after a product is edited, allowing developers to perform custom actions like updating related data.
Creating and Registering an Event Listener
To use OpenCart events, developers need to create an event listener, which is a function or method that responds to a specific event. An event completes the tasks that a controller, a model, a theme override, a language, and a config needs to be achieved in the back-end of the store. Upon startup, the Engine automatically registers triggers, and actions, and sorts orders in both the admin/controller/startup/event.php and catalog/controller/startup/event.php files.
Event listeners are registered using the addEvent method from the Event class. The method takes three parameters: the event name, the class/method to be executed, and the priority of the listener.
Key Parameters for `addEvent` Method
- code: Unique identifier for the event hook.
- trigger: The specific event that triggers the handler.
- action: The method or class that will handle the event.
- description: A brief description of what the event does.
- status: Indicates whether the event is active (1 for enabled, 0 for disabled).
- sort_order: The order in which the event is executed.
Example: Registering an Event
Below is an example of how to register an event in OpenCart:
NOTE : This block of code is written on admin/controller/module/file.
<?php
namespace Opencart\Admin\Controller\Extension\Itmindslabmodule\Module;
class Itmindslabmodule extends \Opencart\System\Engine\Controller{
public function index() {
// your code
}
public function install() {
// registering events to show menu
$this->__registerEvents();
}
protected function __registerEvents() {
$this->model_setting_event->addEvent([
'code' => "IMLShowMenu",
'trigger' => "catalog/view/common/header/after",
'action' => "extension/itmindslab_module/event/itmindslab_module",
'description' => "Customer Account Menu",
'status' => 1,
'sort_order' => 0,
]);
}
public function uninstall(){
$this->__unregisterEvents();
}
protected function __unregisterEvents(){
$this->load->model('setting/event');
$this->model_setting_event->deleteEventByCode('IMLShowMenu');
}
}
Events can be registered in an extension’s install method or directly in the controller if needed.
It’s important to unregister events in the extension’s uninstall method to avoid any unwanted behavior after removing the extension.
After registering the hook, we will see it in the Events list in the admin and can view it. It looks like this:
Handling the Event in the Controller
In the controller file of your module, you would then add a method to handle the event:
This code is written in catalog/controller/event/file.
<?php
namespace Opencart\Catalog\Controller\Extension\Itmindslabmodule\Event;
class Itmindslabmodule extends \Opencart\System\Engine\Controller
{
/**
* index
* @param mixed $route
* @param mixed $data
* @param mixed $output
* @return void
*/
public function index(&$route = false, &$data = array(), &$output = array()): void {
$template_buffer = $this->getTemplateBuffer($route, $output);
$layout = '<li class="list-inline-item">
<a href="#javascript">
<i class="fa-solid fa-cog"></i>
</a>
<span class="d-none d-md-inline">IML Settings</span>
</li>';
$find = '<div class="nav float-start">';
$replace = $find . $layout;
$output = str_replace($find, $replace, $template_buffer);
}
/**
* getTemplateBuffer
* @param mixed $route
* @param mixed $event_template_buffer
* @return string
*/
protected function getTemplateBuffer($route, $event_template_buffer) {
// if there already is a modified template from view/*/before events use that one
if ($event_template_buffer) {
return $event_template_buffer;
}
}
}
The Event looks like in the front end.
Advantages of Events in OpenCart
- Flexibility: Events allow for modifications and extensions without altering core files, thus simplifying development and maintenance.
- Speed: The system is efficient, executing event handlers only when needed.
- Compatibility: The event system is designed to be backward-compatible with previous OpenCart versions.
- Ease of Use: Even developers with minimal experience in extension development can use the event system to add new functionalities or modify existing ones.
Conclusion
The event system in OpenCart is a versatile tool for extending and modifying the platform’s behavior without directly interacting with its core files. By leveraging events, developers can create more maintainable, upgrade-friendly extensions that enhance the overall functionality of an OpenCart store.