Skip to content
Tutorials Center
My learning

Topics

Lesson 25 of 27 ยท Practice

Practice Exercises with Solutions

Twelve graded OpenCart extension exercises on routes, events, settings, totals, escaping, permissions, caching and packaging, each with a runnable PHP stand-in and a solution.

Reading about OpenCart is one thing; building with it is how the ideas stick. This lesson gives you twelve exercises, ordered from easy to harder, covering routes, events, settings, order totals, escaping, permissions, shipping rates, SQL safety, version planning, template fallback and caching. Each exercise has a task, a hint, and a runnable solution you can edit and re-run.

OpenCart itself cannot run on this site, so every solution is a stand-in: a small plain-PHP imitation of the idea (PHP 8.5, one file, no OpenCart classes). The shapes follow what you learned in the events, settings and order total lessons, but the code is not OpenCart code, and the few real OpenCart snippets are read-only. Where a detail changed between 4.0.x releases, the text says so; check the files of the release you target.

Try each task on paper or in your own editor before you open the solution. Ten minutes of struggle teaches more than reading an answer.

flowchart LR
    A["1-3<br/>Routes, events,<br/>settings"] --> B["4-6<br/>Totals, escaping,<br/>packaging"]
    B --> C["7-9<br/>Permissions, rates,<br/>SQL safety"]
    C --> D["10-12<br/>Versions, templates,<br/>cache"]

Twelve exercises in four groups of three.

Exercise 1: resolve a route

Task. An OpenCart 4 route looks like extension/acme/module/badge.save. Write resolveRoute() that returns the controller file, the class name and the method. A route without a method calls index. Also accept the older pipe separator (badge|save), which 4.0.0 and 4.0.1 used before the dot became the standard.

Hint. The first part is always extension, then vendor, extension type and extension name. Names with underscores become StudlyCaps in the class name.

In real OpenCart the controller for the storefront side lives in extension/acme/catalog/controller/module/badge.php and starts like this (read-only):

PHP
namespace Opencart\Catalog\Controller\Extension\Acme\Module;

class Badge extends \Opencart\System\Engine\Controller {
    public function index(): string {
        // build the module HTML and return it
    }
}

Solution.

PHP Exercise 1: route to controller

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 last route is a core route and is rejected by this stand-in; real OpenCart resolves core routes such as product/product the same way but without the extension/vendor prefix. Admin controllers use the same naming under extension/acme/admin/controller/... and need a user_token in the URL.

Exercise 2: events with priority and wildcards

Task. Build a tiny event dispatcher. Each event has a trigger pattern (with * as a wildcard), an action, a status and a sort_order. Dispatching catalog/view/product/product/before must run all enabled matching events in sort_order, passing the arguments by reference so handlers can change them. Register three: one that adds a badge (sort 20), one that upper-cases the title (sort 10), and a disabled one that must never run.

Hint. Convert the pattern to a regular expression with preg_quote and then turn \* into .*. See Events for the real trigger names.

In real OpenCart you register an event in the event table, usually from the extension's install() method (read-only; newer 4.0.x releases take one array, older ones positional arguments, so read admin/model/setting/event.php in your copy):

PHP
$this->model_setting_event->addEvent([
    'code'        => 'acme_badge',
    'description' => 'Adds a badge to product pages',
    'trigger'     => 'catalog/view/product/product/before',
    'action'      => 'extension/acme/event/badge',
    'status'      => true,
    'sort_order'  => 20
]);

Solution.

PHP Exercise 2: a before/after event bus

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 wildcard event ran on both pages; the product-only event ran on one. In real OpenCart before events can also replace the output or stop the default action, which this stand-in leaves out.

Exercise 3: validate and save settings

Task. A module settings form posts module_badge_status, module_badge_name (3 to 64 characters) and module_badge_sort_order (a whole number). Validate the input, return an error per bad field, and on success replace all stored rows for the setting code module_badge. Reject unknown keys instead of saving them.

Hint. OpenCart's editSetting deletes the old rows for a code and inserts the new ones, so a key you stop posting disappears. Only keys that start with the code are accepted.

Real code in the admin controller (read-only):

PHP
if (!$this->user->hasPermission('modify', 'extension/acme/module/badge')) {
    $json['error']['warning'] = $this->language->get('error_permission');
}
if (!$json) {
    $this->load->model('setting/setting');
    $this->model_setting_setting->editSetting('module_badge', $this->request->post);
    $json['success'] = $this->language->get('text_success');
}

Solution.

PHP Exercise 3: settings validation

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 third attempt shows why the prefix check matters: without it, a crafted request could overwrite a core setting through the same form. Details are in Admin Settings Forms.

Exercise 4: a small-order fee total

Task. Write an order total that adds a 2.00 fee when the subtotal is below 20.00, taxed at 20 percent. Work in integer cents and run the pipeline in sort_order: sub-total (1), fee (2), tax (5), total (9). The method signature mirrors OpenCart's getTotal(&$totals, &$taxes, &$total); the real $total is a float in core, while this stand-in uses an integer to make the cent arithmetic exact.

Hint. The fee adds to $total and to the tax pool. The tax extension, which runs later, turns the pool into visible lines. Why integers? See money as integers.

Solution.

PHP Exercise 4: totals pipeline

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.

For the 15.00 cart, tax is 3.00 on items plus 0.40 on the fee, so the total is 20.40. The 25.00 cart skips the fee. Order Total Extensions shows the real class and where rounding can bite.

Exercise 5: escape output in a template

Task. Write render() for templates with {{ name }} placeholders that escapes HTML by default, plus an explicit {{ name|raw }} form that does not. Render a customer name containing markup and a quote, and show why raw is dangerous for user data.

Hint. Twig in OpenCart 4 auto-escapes {{ }} output for HTML templates. The raw filter switches that off for one value, so it belongs only on HTML you built and trust. See Twig Views and Language Files.

Solution.

PHP Exercise 5: auto-escaping and raw

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 raw name line contains a live script tag; in a browser it would run. The right pattern is: escape by default, use raw only for markup your own code produced, and never for request data.

Exercise 6: validate a package

Task. Given the list of paths inside an .ocmod.zip, report problems under these rules, which are a teaching convention and not an official list: install.json must exist at the root; every other path must start with admin/, catalog/ or system/; no path may contain .., start with /, or be a leftover such as .bak, .orig or a trailing ~.

Hint. A package is just a zip. Paths with .. are a zip-slip attack. See Anatomy of an Extension.

Solution.

PHP Exercise 6: package validator

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.

Real OpenCart performs its own checks when installing a package, but your build script should still run something like this so a bad zip never leaves your machine. Packaging, Marketplace and Upgrades covers the full release flow.

Exercise 7: token and permission checks

Task. Admin requests carry a user_token. Write a handler that (1) rejects a wrong token, (2) allows index for users with the access permission on the route, and (3) allows save only with modify. Compare tokens with hash_equals.

Hint. In OpenCart the user group stores two lists per user group, access and modify, of route strings. Reading a page needs access; changing data needs modify.

Solution.

PHP Exercise 7: user_token and permissions

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.

A hidden menu entry is not security: every state-changing method must check permission itself. Security for Extension Developers lists the other checks.

Exercise 8: weight-tier shipping

Task. Implement getQuote() for a shipping method. Orders to DE and FR are in the EU zone: up to 1 kg costs 4.50, up to 5 kg costs 9.00, heavier costs 18.00. Subtotals of 75.00 or more ship free. Other countries get no quote. Return an array shaped like a quote (code, title, quote, sort order, error).

Hint. Use integer cents and grams. The quote array has a nested quote list so one extension can offer several services. See Building a Shipping Extension.

Solution.

PHP Exercise 8: weight tiers and free shipping

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 method signature and the exact quote keys depend on the OpenCart 4.0.x release (some pass the address array, some use the address id), so copy the shape from a core shipping extension of your version.

Exercise 9: break and fix a query

Task. A search function builds SELECT ... WHERE name = '$name' by concatenation. Show an input that returns every row, then fix it. Fix the second query, WHERE product_id = $id, with a typed cast.

Hint. In OpenCart you wrap strings in $this->db->escape() and cast numbers with (int); this lesson's stand-in uses PDO prepared statements to show the same principle with SQLite.

Solution.

PHP Exercise 9: SQL injection and the fix

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 attack returns every product name from the unsafe function. The cast turns 2 OR 1=1 into 2, so only one row comes back. In OpenCart, escape() handles quoting for strings; it does not protect an unquoted number, which is why the cast matters.

Exercise 10: plan an upgrade

Task. An extension ships upgrade steps for 1.1.0, 1.2.0 and 2.0.0. Given an installed version and a target version, list the steps to run, in order. A pre-release such as 1.2.0-beta1 is older than 1.2.0. Refuse a downgrade.

Hint. Use PHP's version_compare. A step runs when installed < step <= target.

Solution.

PHP Exercise 10: upgrade path

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.

Store the installed version in a setting such as module_badge_version and compare it with the version in your code each time the admin page loads or on a dedicated upgrade action.

Exercise 11: template fallback

Task. The storefront looks for a template in the active theme first and falls back to the default theme. Implement resolveTemplate() against a list of existing files and show which file wins for three templates.

Hint. This is the idea behind theme overrides; real OpenCart 4 also lets events change the template route. See Themes and Frontend Customisation.

Solution.

PHP Exercise 11: theme fallback

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 first route is overridden by the theme, the second falls back to the default tree, and the third is missing and must be handled (an empty string or an error log entry, never a fatal error).

Exercise 12: cache a module

Task. A module builds a slow list of badges. Cache it per store and language for 10 minutes, and delete the cache when the settings are saved. Use an injected clock so the test is deterministic.

Hint. OpenCart has a $this->cache object with get, set and delete; the default expiry and what get returns on a miss depend on the version and the cache engine, so read your copy of system/library/cache. Keys must include everything that changes the output.

Solution.

PHP Exercise 12: cache with expiry

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.

Only four builds happened for five calls. A cache you cannot invalidate on save will show stale data after an admin edit; always pair set with a delete in the save action.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which route calls the save method of the badge module in the usual OpenCart 4.0.2+ format?

    The dot separates the route from the method in newer 4.0.x releases; the pipe belongs to 4.0.0 and 4.0.1.
  2. 2. Why must a settings form reject posted keys that do not start with the setting code?

    editSetting writes whatever it is given under one code, so the controller must accept only expected keys.
  3. 3. In the totals exercise, why are amounts kept as integer cents?

    Binary floating point cannot represent most decimal cents exactly, so repeated arithmetic drifts.
  4. 4. What does the (int) cast protect in WHERE product_id = $id?

    Without quotes, escaping cannot neutralise input such as 2 OR 1=1; a cast leaves only the number.
  5. 5. A cached badge list shows old data after an admin edit. What is the likely fix?

    Caches need an explicit invalidation path, or entries stay until they expire.

Summary

  • Routes follow extension/vendor/type/name.method; the class name comes from the same parts.
  • Events run in sort_order, can use wildcard triggers, and handlers change data by reference.
  • Settings forms validate, check modify permission, and accept only keys with the expected prefix.
  • Totals work in integer cents and run in sort order; tax is calculated from a shared pool.
  • Escape by default; use raw only on markup your own code built.
  • Check a valid user_token and the right permission before every state change.
  • Cast numbers, escape strings, and prefer prepared-style patterns where you can.
  • Plan upgrades with version_compare, resolve templates theme-first, and invalidate caches on save.

Ready to test your recall? Continue with OpenCart Developer Interview Questions.