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
Building extensions

Module install and uninstall in OpenCart: tables, events, permissions in 3.0 and 4.1

What the core does when you click "Install", and what the module itself must do in the install and uninstall methods: tables, events, permissions, cleanup.

10 min read OC 3.0 OC 4.1

Installing an 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 → module consists of two parts. First, the core writes the extension into the extension table and grants the current group access rights. Then it calls the install() method of your module's controllerCode that receives a request and prepares data. More in the glossary →, where you create tables, register events, and set initial settings. The uninstall() method must remove everything that install() created, because the core deletes only its own records.

Examples are for OpenCart 4.1; in 4.0.x, model triggers and event handling differ.

What does the core do on its own, and what does it leave to the module?

The "Install" button on the ExtensionsAdditional functionality: a module, a payment or shipping method, a feed, or a theme. They are managed in "Extensions → Extensions." More in the glossary → → Extensions page is handled by the extension type controller: extension/extension/module in OpenCart 3.0 and extension/module in OpenCart 4.1. The mechanism is the same for other types. The core's sequence of actions is as follows:

  1. It checks the modify permission for the type controller. Without it, nothing happens.
  2. It adds a row to the extension table. OpenCart 4.1: first it checks that the controller file exists in extension/{папка}/admin/controller/{тип}/, and it also records the folder name.
  3. It adds the access and modify permissions for the extension route to the current user's group.
  4. OpenCart 4.1: it registers the controller, model, and system namespaces of this folder with the autoloader, along with the paths to templates, language files, and configs.
  5. It calls the install method of your controller, if it exists: extension/module/{код}/install in 3.0 or extension/{папка}/module/{код}.install in 4.1.

Note: only the group of the person who clicked "Install" receives the permissions. Other administrators (managers, content editors) must be granted them manually in System → Users → User Groups. Permissions are stored in the permission column of the user_group table as JSON with access and modify arrays. For more details, see the article how a user group checks access to a module.

Before your install(), the core creates nothing in the setting table. Therefore, until the administrator saves the settings form, the module_{код}_status key does not exist, and the storefrontWhat the customer sees: the home page, categories, product page, and cart. More in the glossary → treats the module as disabled. This is safe default behavior, and it's better not to break it with automatic enabling.

How does "Extension Installer" differ from the "Install" button?

Newcomers often confuse two steps whose names in the admin panel are similar. The Extensions → Installer page works with the .ocmod.zip archive and files on disk. The "Install" button in the Extensions → Extensions list registers an extension that already exists in the database. Your module's install() method calls only the second step.

  • OpenCart 3.0: The Installer unpacks the archive into a temporary directory and moves the contents of the upload/ folder into the store's directories: admin/, catalog/, image/, system/. If the archive contains install.xml, an OCMOD modification is created from it. After that, the module appears in the list of its type, and it must be installed separately with the button.
  • OpenCart 4.1: the archive first goes to storage/marketplace/. To display the name and version, the Installer reads install.json from it. The Installer's install button unpacks the files into extension/{код}/ and records each path in the database so that it can later delete these files precisely. Uninstalling in the Installer removes these files and directories.

The practical consequence for developers: between uploading the archive and clicking "Install," the module is already on disk but has no row in extension, no permissions, and no tables. Module controllers that access their tables before installation (for example, through a manually registered event) will fail with an SQL error. Therefore, everything that depends on the database must be registered only in install(). The structure of the archive is covered in the topic on packaging a module.

How do you create module tables in install()?

The install() method is a regular public method of the admin controller, with no parameters. It's convenient to create tables through the module's model so that the controller stays thin. Always use DB_PREFIX and CREATE TABLE IF NOT EXISTS: this way the module survives reinstallation after a failed attempt and stores with a non-standard prefix.

Example

<?php
// OpenCart 3.0: admin/model/extension/module/mymodule.php
class ModelExtensionModuleMymodule extends Model {
	public function install() {
		$this->db->query("CREATE TABLE IF NOT EXISTS `" . DB_PREFIX . "mymodule_log` (
			`log_id` INT(11) NOT NULL AUTO_INCREMENT,
			`order_id` INT(11) NOT NULL,
			`message` TEXT NOT NULL,
			`date_added` DATETIME NOT NULL,
			PRIMARY KEY (`log_id`),
			KEY `order_id` (`order_id`)
		) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci");
	}

	public function uninstall() {
		$this->db->query("DROP TABLE IF EXISTS `" . DB_PREFIX . "mymodule_log`");
	}
}

Character encoding and collation of core tables depend on the release. In 3.0.5.1 and 4.1.0.4 these are utf8mb4 and utf8mb4_unicode_ci, and in 3.0.4.1 they are utf8 and utf8_general_ci. For module tables, specify COLLATE=utf8mb4_unicode_ci or don't specify COLLATE at all, in which case the table takes the database's collation. Different collations in JOIN text fields between your table and, for example, product_description cause the error "Illegal mix of collations". In 3.0.4.1, such a conflict will occur with any module table joined to utf8mb4, while JOIN on numeric ids (INT) works without problems. Another 3.0 pitfall: the database connection runs in utf8 (set_charset('utf8')), so emojis won't be saved even in the utf8mb4 table.

OpenCart 4.1: the model lives in extension/{папка}/admin/model/module/mymodule.php with the Opencart\Admin\Model\Extension\{Папка}\Module namespace, and the methods have types (public function install(): void). The SQL is the same.

How do you register events during installation?

If the module changes the core's behavior, that is, adds data to a templateA display file: in 2.x it is .tpl, and in 3.0 and 4.1 it is .twig. More in the glossary →, reacts to order creation, or extends the menu, register an event in install(). The event model setting/event differs noticeably between versions.

OpenCart 3.0OpenCart 4.1
AddaddEvent($code, $trigger, $action, $status = 1, $sort_order = 0)addEvent(array $data): int with keys code, description, trigger, action, status, sort_order
DeletedeleteEventByCode($code)deleteEventByCode(string $code)
Enable / disableenableEvent($event_id), disableEvent($event_id)editStatus($event_id, $status), editStatusByCode($code, $status)
Trigger formatcatalog/model/account/customer/addCustomer/aftercatalog/model/account/customer.addCustomer/after
Action formatextension/module/mymodule/onAddCustomerextension/mymodule/module/mymodule.onAddCustomer

The main difference is that in 4.1 the method is separated from the route by a dot in both the trigger and the action. An event code carried over from 3.0 without changes will simply never fire, and you won't see any error.

Example

// OpenCart 4.1, контролер extension/mymodule/admin/controller/module/mymodule.php
public function install(): void {
	if ($this->user->hasPermission('modify', 'extension/module')) {
		$this->load->model('setting/event');

		$this->model_setting_event->deleteEventByCode('mymodule_order');

		$this->model_setting_event->addEvent([
			'code'        => 'mymodule_order',
			'description' => 'Mymodule: лог нових замовлень',
			'trigger'     => 'catalog/model/checkout/order.addHistory/after',
			'action'      => 'extension/mymodule/module/mymodule.onAddHistory',
			'status'      => true,
			'sort_order'  => 0
		]);
	}
}

Calling deleteEventByCode() before addEvent() protects against duplicates. The core does not check the uniqueness of code, and after several installations your handler would run two or three times. The event code should begin with the module code: then uninstall() is guaranteed to remove only your records. Registered events are visible in Extensions → Events.

Extensions → Events: a module event with its code, trigger, and status
Extensions → Events: a module event with its code, trigger, and status · OpenCart 4.1.0.4

The event mechanism itself, before/after, and the execution order are described separately. The key point here is this: registering an event is part of installation, and removing it is part of uninstallation.

What should uninstall() do?

The "Delete" button starts the reverse process. The core removes the row from extension and all keys of the {тип}_{код} group from setting, and for modules also the instances from the module table. After that, it calls your uninstall(). The rest is up to you.

  • Events. deleteEventByCode() for each code the module registered. A forgotten event after the module is removed will call a nonexistent controller on every trigger.
  • Tables. Decide consciously whether to delete data. A log can be wiped, but payment history or order links are better kept: administrators often remove a module in order to reinstall it.
  • Settings under a different code. If the module wrote something to setting under a code different from {тип}_{код}, the core won't find it.
  • Permissions. OpenCart 3.0: the type controller itself removes the module's route permissions from all groups. OpenCart 4.1: the standard module controller does not remove permissions, so if needed, remove them via removePermission($user_group_id, $type, $route).
  • Files. "Delete" does not remove the module's files. OpenCart 4.1: files are removed separately in Extensions → Extension Installer.

How do you update a module if install() has already run?

The core calls install() only after the "Install" button is clicked. If you've re-uploaded the files with a new version, the method won't run, and new columns or events will appear only after a full reinstallation. And reinstalling via "Delete" wipes the settings.

Therefore, perform schema updates separately from the first installation:

  1. Store the module's schema version in setting, for example under the key module_mymodule_db_version. Caution: editSetting('module_mymodule', …) first deletes the entire group for this store_id when the form is saved, and then inserts only the keys that were passed. So the version must be passed on every save, for example via a hidden form field or by appending it to the POST in the controller. Otherwise it will be erased, and migrations will run again. Another option: store the version under a separate code, but then uninstall() must remove that record itself.
  2. Write install() so that it can run repeatedly without errors: IF NOT EXISTS, a column check before ALTER TABLE, deleteEventByCode() before addEvent().
  3. Run the same migration steps when the administrator opens the settings form and the stored version is lower than the current one. This is the most reliable point, because after an update the module is almost always opened.

The topic of migrations between module versions has its own article. The above describes the minimum without which updates break clients' stores.

How do you verify that installation and removal work cleanly?

Before a release, run a simple cycle on a clean store with error output enabled:

  1. Install the module and check the extension and event tables, your own tables, and the group permissions.
  2. Save the settings and make sure the keys appeared in setting with the correct code.
  3. Remove the module and check that no rows with your code remain in event, and no rows for your group remain in setting.
  4. Install the module again. Reinstallation should not fail with "Table already exists" or create duplicate events.
  5. Log in as a user from another group and make sure that without permissions the module is inaccessible, and with permissions it works.

This cycle takes a few minutes and catches most complaints of the "after removing the module the site shows an error" kind. The general structure of a module to which these methods are added is described in the article anatomy of an extension in 3.0 and 4.1, and a working template is in the material the first module from scratch.

Summary

  • On installation, the core only registers the extension and grants permissions to the current user's group. Tables, events, and initial settings are created by your install().
  • On removal, the core deletes the record in extension, the group settings, and the module instances. Events, tables, and, in 4.1, permissions are removed by your uninstall().
  • In 4.1, events are written as an array and with a dot before the method in the trigger and action.
  • install() should be idempotent, and schema updates are best moved into a separate version check.

Other topics in this section are collected on the page creating extensions for OpenCart.

FAQ

Can I call install() manually without removing the module?
Yes, it is a regular controller method. You can open it by route with user_token or call it from another method. This is a convenient way to run migrations after an update.
Why can't other administrators see the module after installation?
Only the group of the user who installed it receives permissions. Add the module route to access and modify for the required groups in the user group settings.
Do I need to clear the cache after install?
No, not for tables and events: events are read from the database on every request. If the module changes templates through OCMOD modifications, refresh the modifications after installation.
What happens if install() throws an exception midway?
The core entries in extension and the permissions will already be created, but your part will only be partially done. That is why install() should be written to be idempotent, so after a fix you can simply install the module again.
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.