Skip to content
Tutorials Center
My learning

Topics

Lesson 8 of 27 ยท The admin side

Install, Uninstall and Permissions

How an OpenCart 4 extension installs: install() and uninstall(), creating tables, user group access and modify permissions, events on install and schema upgrades.

Copying files into an OpenCart store does not make an extension work. The store also has to know the extension exists, the administrator's group must be allowed to open its pages, and any database tables or events it needs must be created. All of that happens in a short, well-defined step: the install. Its mirror image, the uninstall, must leave the store as clean as before.

Getting this lifecycle right is what separates a tidy extension from one that leaves orphan tables, dead permissions and broken events behind. This lesson covers the two stages of installing in OpenCart 4, what the core does for you, what you must do yourself in install() and uninstall(), how permissions are stored, and how to upgrade a database schema when you release a new version. Real OpenCart code is read-only here. The runnable examples are stand-ins on SQLite. For the file layout see Anatomy of an Extension, and for the settings page that comes next see Admin Settings Forms.

Two stages: upload, then install

OpenCart 4 separates getting the files in from switching the extension on.

  1. Upload with the extension installer. In the admin you open Extensions, Installer, and upload an .ocmod.zip. The core unpacks it into extension/<vendor>/ and records it in the extension_install table. At this point the code is on disk, but nothing is active. You can also uninstall (remove the files) from the same screen.
  2. Install the extension type entry. Under Extensions, choose the type (Modules, Payments, Shipping, Order Totals) and press the green plus button next to your extension. This is the install this lesson is about.

Pressing the button makes the core controller for that type do roughly the following. The exact code differs a little between 4.0.x versions, so treat this as the general shape and read the controller for your version:

  1. Insert a row in the extension table with the extension folder name, the type and the code.
  2. Add access and modify permission for your page to the current user's group.
  3. Call your own install() method, if the controller has one.

When you press the red minus button, the core removes the extension row and the permissions, and calls your uninstall().

flowchart TD
    A["Upload .ocmod.zip<br/>(Installer)"] --> B["Files copied to<br/>extension/vendor/"]
    B --> C["Extensions list:<br/>press Install"]
    C --> D["Core inserts extension row<br/>and permissions"]
    D --> E["Your install() runs:<br/>tables, events, defaults"]
    E --> F["Open the settings page,<br/>set status to enabled"]

Uploading and installing are two separate steps. Your install() code runs in the second one.

Writing install() and uninstall()

The two methods live in the same admin controller as the settings page. Here is a typical pair for a module that stores its own table and one event. It is read-only, because it needs a running store.

PHP
<?php
namespace Opencart\Admin\Controller\Extension\Acme\Module;

class Hello extends \Opencart\System\Engine\Controller {
    public function install(): void {
        $this->load->model('extension/acme/module/hello');
        $this->model_extension_acme_module_hello->install();

        $this->load->model('setting/event');
        $this->model_setting_event->addEvent([
            'code'        => 'acme_hello_banner',
            'description' => 'Adds a greeting to the home page',
            'trigger'     => 'catalog/view/common/home/after',
            'action'      => 'extension/acme/event/hello',
            'status'      => 1,
            'sort_order'  => 0
        ]);
    }

    public function uninstall(): void {
        $this->load->model('setting/event');
        $this->model_setting_event->deleteEventByCode('acme_hello_banner');

        $this->load->model('setting/setting');
        $this->model_setting_setting->deleteSetting('module_hello');

        $this->load->model('extension/acme/module/hello');
        $this->model_extension_acme_module_hello->uninstall();
    }
}

The model that does the SQL work sits next to it, in extension/acme/admin/model/module/hello.php:

PHP
<?php
namespace Opencart\Admin\Model\Extension\Acme\Module;

class Hello extends \Opencart\System\Engine\Model {
    public function install(): void {
        $this->db->query("CREATE TABLE IF NOT EXISTS `" . DB_PREFIX . "acme_hello` (
            `hello_id` INT(11) NOT NULL AUTO_INCREMENT,
            `customer_id` INT(11) NOT NULL,
            `message` VARCHAR(255) NOT NULL,
            `date_added` DATETIME NOT NULL,
            PRIMARY KEY (`hello_id`),
            KEY `customer_id` (`customer_id`)
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci");
    }

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

Several habits make these methods reliable:

  • Use DB_PREFIX and a vendor prefix on table names (acme_hello), so you never clash with core tables or other extensions.
  • Make install idempotent. CREATE TABLE IF NOT EXISTS and DROP TABLE IF EXISTS mean a half-finished install or a repeated click does not crash.
  • Give events a unique code that starts with your vendor name. You delete by code on uninstall, so the code is your handle on exactly your rows. Events themselves are explained in Events.
  • Clean up settings. Removing the extension row does not necessarily delete your module_hello_* settings. Call deleteSetting('module_hello') in uninstall() if you want a clean slate. Some developers deliberately keep data on uninstall so merchants do not lose records by accident; if you do that, say so in the documentation.
  • Do not drop merchant data silently. Dropping a table on uninstall erases orders or logs your extension collected. For anything valuable, consider asking the merchant (a setting such as "delete data on uninstall") before dropping.

The signature of addEvent differs between early 4.0.x releases (separate arguments) and later ones (one array). Read admin/model/setting/event.php in the exact version you target.

How permissions are stored

OpenCart stores permissions per user group, in the user_group table. The permission column holds a JSON document with two lists of routes:

JSON
{
  "access": ["common/dashboard", "extension/acme/module/hello"],
  "modify": ["extension/acme/module/hello"]
}

access means the user may open (read) the page. modify means the user may save changes. The admin menu shows a page only if the route is under access, and a well-written save() refuses without modify (see Admin Settings Forms).

The core adds both permissions for your own group when you install, otherwise you would lock yourself out of the page you just installed. Other groups, such as a "Support" group, do not get anything automatically. An administrator must open Users, User Groups and tick the pages for them. When your extension has several routes (for example a settings page plus a separate log page), the core only adds the main extension route; if your install must grant access to the others, do it in your own install() through the user group model:

PHP
$this->load->model('user/user_group');
$this->model_user_user_group->addPermission($this->user->getGroupId(), 'access', 'extension/acme/module/hello_log');
$this->model_user_user_group->addPermission($this->user->getGroupId(), 'modify', 'extension/acme/module/hello_log');

and remove them again in uninstall() with removePermission.

Upgrading a schema

Neither the installer nor the extension table keeps a schema version for you, so a new release that needs a new column cannot rely on install() running again: the store already has the extension installed. The usual solution is to keep your own version number, for example in a setting, and compare it when something loads, or when the merchant opens your settings page:

  1. Store module_hello_schema (an integer) at install time.
  2. On the settings page index(), compare it with the highest migration your code knows.
  3. Run each missing migration in order, then store the new number.

Write each migration so it can safely run twice, by checking information_schema or using ADD COLUMN IF NOT EXISTS where your MySQL or MariaDB version allows it. Never edit an old migration after release; add a new one. The same idea appears again in Packaging, Marketplace and Upgrades.

Try it: an installer that migrates and cleans up

This stand-in is not OpenCart. It imitates the idea of an idempotent install, a version number stored next to the data, ordered migrations, and an uninstall that removes everything.

PHP Install, upgrade and uninstall with migrations

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The second call to migrate(1) applies nothing, which is what an idempotent install should do. The upgrade added a column and an index without losing the stored row.

Now permissions. OpenCart keeps them as a JSON document per group; this stand-in shows the add, check and remove operations and why a second group is unaffected.

PHP User group permissions as JSON

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Group 2 never receives the new route. This is why support staff often report "the page is missing" after a new extension is installed: someone has to tick the boxes in User Groups.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What are the two stages of putting an extension into use in OpenCart 4?

    The Installer unpacks the files and records the package. The extension list's Install button registers the extension, adds permissions and runs your install() method.
  2. 2. Why should install() use CREATE TABLE IF NOT EXISTS?

    Idempotent SQL means running install twice, or after a partial failure, does not crash. The same reasoning applies to DROP TABLE IF EXISTS in uninstall().
  3. 3. A new Support user group cannot see your extension's page. What is the most likely cause?

    The core adds permissions only for the installing user's group. Other groups need the route ticked under User Groups.
  4. 4. How do you handle a new column in version 1.2 of an extension that is already installed?

    install() does not run again for an installed extension. Store a schema version, compare it when needed, and apply ordered, repeatable migrations.

Summary

  • Installing has two stages: upload the package with the installer, then press Install in the extension list.
  • The core registers the extension and grants access and modify to the installing user's group, then calls your install().
  • Create tables with DB_PREFIX and a vendor prefix, make SQL idempotent, and give events and permissions names you can remove later.
  • uninstall() should remove your events, settings, permissions and tables, but consider keeping valuable merchant data.
  • Permissions live as JSON in user_group.permission; other groups need to be granted pages by an administrator.
  • Keep your own schema version and apply ordered migrations when upgrading.

Next, learn how to change core behavior without editing core files in Events.