Skip to content
Tutorials Center
My learning

Topics

Lesson 27 of 27 ยท Interviews and reference

OpenCart Extension Cheat Sheet

A quick OpenCart 4 extension reference: folder layout, route format, event triggers, registry calls, extension type contracts, setting key prefixes, and security and release checklists.

This page is a lookup table, not a lesson. When you cannot remember whether the route separator is a dot or a pipe, which prefix a payment setting uses, or what an event trigger looks like, come here. It targets OpenCart 4.0.x and links back to the lessons that explain each idea. Method signatures and a few names changed between 4.0.x releases, so treat this page as a map and confirm exact details in the core files of the release you support (look at a core extension of the same type, such as extension/opencart/).

OpenCart cannot run on this site, so all real code and trees here are read-only. The two small runnable examples at the end are plain-PHP stand-ins: a name generator that applies the naming rules, and a rough audit script for the security checklist. They are not OpenCart code.

flowchart LR
    A["Where is the file?"] --> F["Folder layout"]
    B["How do I call it?"] --> R["Routes and registry"]
    C["How do I hook in?"] --> E["Events"]
    D["Am I done?"] --> K["Checklists"]

Jump to the section that matches your question.

Folder layout

An extension lives in its own vendor folder. This is the layout of a module called badge from vendor acme (read-only):

TEXT
extension/acme/
  install.json                          name, version, author, link
  admin/
    controller/module/badge.php         settings page: index(), save()
    language/en-gb/module/badge.php     admin text
    model/module/badge.php              admin-side queries (optional)
    view/template/module/badge.twig     settings form
  catalog/
    controller/module/badge.php         storefront: index()
    language/en-gb/module/badge.php     storefront text
    model/module/badge.php              storefront queries (optional)
    view/template/module/badge.twig    storefront HTML
  system/
    library/                            shared helper classes (optional)

When you ship the extension, the zip is named something.ocmod.zip and carries the same tree with install.json at its root. See Anatomy of an Extension and Packaging, Marketplace and Upgrades.

Folder Holds
extension/{vendor}/ Everything your extension ships
admin/, catalog/ The two applications; each has controller, model, view and language
system/ Shared libraries and helpers
storage/ (outside the web root) Logs, cache, uploads, downloads, modification output
config.php, admin/config.php Paths, database settings and DB_PREFIX

Routes

Part Example Notes
Extension route extension/acme/module/badge extension / vendor / type / name
With a method extension/acme/module/badge.save Dot in 4.0.2 and later; the pipe | was used in 4.0.0 and 4.0.1
Default method index Used when the route has no method
Storefront URL index.php?route=extension/acme/module/badge Pretty URLs use SEO keywords instead
Admin URL index.php?route=...&user_token=... A missing or wrong user_token sends you to login
Class Opencart\Catalog\Controller\Extension\Acme\Module\Badge Admin uses Opencart\Admin\...
Model call $this->load->model('extension/acme/module/badge') Then $this->model_extension_acme_module_badge
Language call $this->load->language('extension/acme/module/badge') Then $this->language->get('key')

More in Routing and Controllers.

Setting keys by extension type

Type Key pattern Example
module module_{name}_{field} module_badge_status
payment payment_{name}_{field} payment_hosted_pay_sort_order
shipping shipping_{name}_{field} shipping_weight_zone_status
total total_{name}_{field} total_handling_status
theme theme_{name}_{field} theme_shoptheme_status

Save a form with $this->model_setting_setting->editSetting('module_badge', $this->request->post) and read values with $this->config->get('module_badge_status'). editSetting replaces all rows for the code, so post every field. See Admin Settings Forms.

Registry calls you will use daily

Call Purpose
$this->request->get['id'], ->post['name'] Input (always validate and escape)
$this->session->data['key'] Session values
$this->config->get('config_language_id') Settings
$this->load->model('x/y'), ->language('x/y'), ->view('x/y', $data) Loader
$this->language->get('text_key') Translated text
$this->db->query($sql) Run SQL; result has ->row, ->rows, ->num_rows
$this->db->escape($string) Escape a string for SQL; cast numbers with (int)
$this->db->getLastId(), ->countAffected() After insert, update or delete
DB_PREFIX . 'table' Table prefix in queries
$this->url->link('route', 'arg=1') Build a URL
$this->response->setOutput($html) Send output; ->redirect($url) redirects
$this->cache->get($key), ->set($key, $value), ->delete($key) Cache
$this->log->write('message') Write to the error log
$this->customer->isLogged(), $this->cart->getProducts() Storefront state
$this->user->hasPermission('modify', $route) Admin permission check
$this->currency->format($amount, $code) Format money for display
$this->document->setTitle($title) Page title

Details in Models, the Registry and the Database.

Events

Part Example
Controller trigger catalog/controller/product/product/before
View trigger catalog/view/product/product/after (route of the Twig template)
Model trigger catalog/model/checkout/order/addHistory/after (model route plus method)
Language trigger catalog/language/product/product/after
Admin triggers Same patterns starting with admin/
Wildcards catalog/view/*/before matches every storefront view; use sparingly
Action A route such as extension/acme/event/badge, optionally with .method
Fields code, description, trigger, action, status, sort_order

Handlers receive the route and the arguments by reference (and, for after events, the output). Register events in install() and remove them in uninstall() by code, so uninstalling leaves nothing behind. Read Events first; reach for OCMOD only when no trigger exists.

Extension type contracts

Type You provide Core calls
module Admin settings controller; catalog controller index() returning HTML Layout rendering for a position
payment Admin settings; catalog controller (confirm step) and model with the method list for the address Checkout payment step, confirm, callbacks
shipping Catalog model getQuote($address) returning the quote array Checkout shipping step
total Catalog model getTotal(&$totals, &$taxes, &$total) Cart and checkout total calculation, in sort_order
theme Template files and theme settings Template resolution

Names and signatures here vary by 4.0.x release (for example the payment method list method and the type of $total); copy the shape from a core extension of the same type in your target version. See Modules and Layouts, Building a Payment Extension, Building a Shipping Extension and Order Total Extensions.

Minimal quote array shape for shipping (read-only):

PHP
return [
    'code'       => 'weight_zone',
    'title'      => 'Weight and zone',
    'quote'      => ['eu' => ['code' => 'weight_zone.eu', 'title' => 'EU delivery', 'cost' => 4.50, 'tax_class_id' => 0, 'text' => '4.50']],
    'sort_order' => 1,
    'error'      => false
];

Security checklist

  • Every {{ }} output in Twig is auto-escaped; |raw is used only on markup your code built.
  • Every string in SQL goes through $this->db->escape(); every number is cast with (int) or (float).
  • Admin actions check hasPermission('modify', ...), and the page needs a valid user_token.
  • Posted settings are limited to the keys you expect.
  • Uploads are checked for type, size and name, and stored outside the web root where possible.
  • Secrets (API keys, signing secrets) are never printed in templates, logs or error messages.
  • Payment and webhook callbacks verify a signature with hash_equals, compare amounts, and are idempotent.
  • Custom state-changing storefront forms use their own anti-forgery token; do not assume core adds one for you.
  • Error display is off in production; errors go to the log.

See Security for Extension Developers.

Release checklist

  • install.json has the right name, version, author and link.
  • install() creates tables and events; uninstall() removes events and, if you choose, tables.
  • Upgrade steps are idempotent and run in version order.
  • Tested on a clean store and on the oldest and newest 4.0.x you claim to support.
  • No core files edited; no leftover .bak files or debug output in the zip.
  • Language files exist for English (en-gb) and every key used in Twig is defined.
  • Caches are invalidated on settings save.
  • A changelog and licence are included.

Two runnable stand-ins

Naming generator

PHP Names for a new extension

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.

Use the generator as a quick check that your folder names, class names and setting keys agree: a mismatch in any one of them is the most common reason a new extension "does nothing".

A rough security audit

PHP Spot risky lines with a tiny audit

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.

This audit is a heuristic that only reads lines of text; it cannot understand code, and real review needs a human. Use it as a reminder, not as proof of safety.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which setting key matches a payment extension named hosted_pay?

    Setting keys use the extension type as a prefix, then the name, then the field.
  2. 2. What is the usual route for the save method of extension/acme/module/badge in 4.0.2 and later?

    The dot separates the method; the pipe was used in 4.0.0 and 4.0.1.
  3. 3. Where should logs, cache and uploads live?

    Keeping storage outside the web root stops visitors from requesting those files by URL.
  4. 4. Why is a wildcard event trigger risky?

    A pattern such as catalog/view/*/before matches many routes, and the handler runs on each.
  5. 5. Which check must be present on every admin action that changes data?

    The token proves the session; the modify permission proves this user may change this extension.

Summary

  • Extensions live in extension/{vendor}/ with admin/, catalog/ and system/ inside; install.json sits at the package root.
  • Routes are extension/vendor/type/name plus .method (4.0.2 and later).
  • Setting keys start with the extension type: module_, payment_, shipping_, total_, theme_.
  • Events have a trigger, an action, a status and a sort order; keep triggers specific.
  • Each extension type has its own contract; copy the shape from a core extension of your target version.
  • Check escaping, casts, user_token, modify permission and callback signatures before you release.

That completes the track. Revisit Practice Exercises with Solutions to test yourself, or start again from OpenCart 4 and Extension Development.