Skip to content
Tutorials Center
My learning

Topics

Lesson 21 of 27 ยท Real-world projects

Project: Weight and Zone Shipping Method

Build a complete OpenCart shipping extension: per geo zone weight tiers, a free-over threshold, admin settings, an install script and tests for the rate logic.

Many small shops ship by weight and destination: a light parcel to a nearby zone costs a few dollars, a heavy one to a distant zone costs more, and orders above a certain value ship free. OpenCart ships with a weight-based method, but real projects often need a twist: different tiers per geo zone, a free-shipping threshold that depends on the zone, or a limit on the maximum parcel weight. In this project you build a custom shipping extension, Acme Weight Zone, from the settings screen to the rate calculation.

You already know the pieces: the shipping extension contract, admin settings forms, install and uninstall and testing logic outside controllers. Here they come together. OpenCart cannot run on this site, so the extension files are read-only code. The calculation is plain PHP with no OpenCart dependencies, so the rate engine runs live in the TryIts, and it is the part we test. Money is handled as integer cents as explained in Money as Integers, and general rate ideas are in Shipping Rates.

The design

flowchart TD
    C["Checkout asks for quotes"] --> M["Model getQuote(address)"]
    M --> Z["Find geo zones<br/>matching the address"]
    Z --> R["Rate engine<br/>(pure PHP)"]
    S["Settings per zone:<br/>tiers, free over, status"] --> R
    W["Cart weight and subtotal"] --> R
    R --> Q["Quote array<br/>in OpenCart's shape"]

The model gathers inputs from OpenCart. The rate engine only does arithmetic, so it can be tested without OpenCart.

The key design decision is the split: everything that touches OpenCart (settings, address, cart, formatting) lives in the model, and everything that decides the price lives in a small class with no dependencies. That class can be tested in a second, and it will not break when OpenCart changes.

Folder layout

TEXT
extension/acme/
  install.json
  admin/
    controller/shipping/weightzone.php
    language/en-gb/shipping/weightzone.php
    view/template/shipping/weightzone.twig
  catalog/
    model/shipping/weightzone.php
    language/en-gb/shipping/weightzone.php
  system/library/acme/weightzone/rateengine.php

(system/library is one place for a helper class; confirm in your OpenCart version how library classes are autoloaded and namespaced, as covered in Anatomy of an Extension.)

Settings keys

Settings are stored in the setting table, with the code shipping_weightzone. Per geo zone, there is a status and a rates string; globally, a tax class, a free-over amount and a sort order:

Key Meaning
shipping_weightzone_status master switch for the method
shipping_weightzone_{geo_zone_id}_status is this zone active
shipping_weightzone_{geo_zone_id}_rates tiers, for example 1:4.00,5:8.50,20:15.00
shipping_weightzone_{geo_zone_id}_free_over order total at which shipping is free (empty = never)
shipping_weightzone_tax_class_id tax class for the quote
shipping_weightzone_sort_order position among shipping methods

The weight:cost format mirrors the way OpenCart's own weight method stores rates. Each pair means "up to this many kilograms (or the store's weight unit), the cost is this". The pairs must be in ascending weight order, which our parser enforces.

The rate engine (runnable)

First, parsing and validating the tiers, and matching an address to geo zone rows. Both are reused by the settings screen and the model.

PHP Parse tiers and match an address to a zone

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.

Now the engine itself. It takes the zone configuration, the cart weight in grams and the order subtotal in cents, and returns the cost or null when no rate applies (zone disabled, parcel heavier than the largest tier). The wrapper function turns a result into the quote array shape that OpenCart's checkout expects.

PHP The rate engine and OpenCart's quote shape

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.

Notice that a missing quote is null, not zero. A free rate and "we cannot ship this" must never be confused.

The catalog model (read-only)

The model gathers OpenCart's data and calls the engine. This is real OpenCart 4 style code. The class name and method signature follow the conventions of recent 4.0.x releases, but verify them against the shipping extensions bundled with the version you target, since these details have changed between releases.

PHP
<?php
namespace Opencart\Catalog\Model\Extension\Acme\Shipping;

use Acme\WeightZone\RateEngine;

class WeightZone extends \Opencart\System\Engine\Model {
    public function getQuote(array $address): array {
        $this->load->language('extension/acme/shipping/weightzone');

        $zones = [];
        $query = $this->db->query("SELECT * FROM `" . DB_PREFIX . "geo_zone` ORDER BY `name`");

        foreach ($query->rows as $result) {
            $id = (int)$result['geo_zone_id'];

            if (!$this->config->get('shipping_weightzone_' . $id . '_status')) {
                continue;
            }

            $match = $this->db->query("SELECT * FROM `" . DB_PREFIX . "zone_to_geo_zone`
                WHERE `geo_zone_id` = '" . $id . "'
                AND `country_id` = '" . (int)$address['country_id'] . "'
                AND (`zone_id` = '" . (int)$address['zone_id'] . "' OR `zone_id` = '0')");

            if ($match->num_rows) {
                $free = $this->config->get('shipping_weightzone_' . $id . '_free_over');

                $zones[$id] = [
                    'status'    => true,
                    'rates'     => (string)$this->config->get('shipping_weightzone_' . $id . '_rates'),
                    'free_over' => $free === '' || $free === null ? null : (int)round((float)$free * 100),
                ];
            }
        }

        if (!$zones) {
            return [];
        }

        $weightGrams = (int)round($this->cart->getWeight() * 1000);   // tiers are in the store's weight unit (kilograms here)
        $subtotal    = (int)round($this->cart->getSubTotal() * 100);

        $engine = new RateEngine($zones);
        $cost   = null;
        foreach (array_keys($zones) as $id) {
            $candidate = $engine->cost($id, $weightGrams, $subtotal);
            if ($candidate !== null && ($cost === null || $candidate < $cost)) {
                $cost = $candidate;   // cheapest matching zone wins
            }
        }

        if ($cost === null) {
            return [];
        }

        $taxClassId = (int)$this->config->get('shipping_weightzone_tax_class_id');
        $amount     = $cost / 100;

        return [
            'code'       => 'weightzone',
            'title'      => $this->language->get('text_title'),
            'quote'      => [
                'weightzone' => [
                    'code'         => 'weightzone.weightzone',
                    'title'        => $cost === 0 ? $this->language->get('text_free') : $this->language->get('text_description'),
                    'cost'         => $amount,
                    'tax_class_id' => $taxClassId,
                    'text'         => $this->currency->format(
                        $this->tax->calculate($amount, $taxClassId, $this->config->get('config_tax')),
                        $this->session->data['currency']
                    )
                ]
            ],
            'sort_order' => (int)$this->config->get('shipping_weightzone_sort_order'),
            'error'      => false
        ];
    }

}

Three details deserve a note. The cart's weight is expressed in the store's weight unit. This project simply declares that the tiers use the same unit (kilograms by default) and turns it into whole grams, so comparisons never involve floats. If your products use mixed weight classes, $this->cart->getWeight() already converts them to the store's default unit. Prices are cast to cents with round() to avoid float errors, as in Money as Integers. And every id that enters SQL is cast to int, in line with Security for Extension Developers.

The admin settings controller (read-only)

The settings screen shows one row per geo zone, with a status switch, a rates field and a free-over field. The save method validates before it writes.

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

class WeightZone extends \Opencart\System\Engine\Controller {
    public function save(): void {
        $this->load->language('extension/acme/shipping/weightzone');

        $json = [];

        if (!$this->user->hasPermission('modify', 'extension/acme/shipping/weightzone')) {
            $json['error']['warning'] = $this->language->get('error_permission');
        }

        $this->load->model('localisation/geo_zone');

        foreach ($this->model_localisation_geo_zone->getGeoZones() as $zone) {
            $id    = (int)$zone['geo_zone_id'];
            $rates = (string)($this->request->post['shipping_weightzone_' . $id . '_rates'] ?? '');

            if ($rates !== '' && !preg_match('/^\s*\d+(\.\d+)?\s*:\s*\d+(\.\d{1,2})?\s*(,\s*\d+(\.\d+)?\s*:\s*\d+(\.\d{1,2})?\s*)*$/', $rates)) {
                $json['error']['rates_' . $id] = $this->language->get('error_rates');
            }
        }

        if (!$json) {
            $this->load->model('setting/setting');
            $this->model_setting_setting->editSetting('shipping_weightzone', $this->request->post);

            $json['success'] = $this->language->get('text_success');
        }

        $this->response->addHeader('Content-Type: application/json');
        $this->response->setOutput(json_encode($json));
    }
}

The regular expression only checks the shape. Ascending order is checked by the same logic as the stand-in parser, which you would call from the controller as well, so the admin sees the error immediately rather than a quote that mysteriously disappears.

The install script (read-only)

A shipping extension that uses only settings needs no tables. It does need sensible defaults and a clean uninstall. Defaults are stored when the merchant first saves, so a small install() in the admin controller can store a disabled state and a starter tier set:

PHP
<?php
public function install(): void {
    $this->load->model('setting/setting');

    $this->model_setting_setting->editSetting('shipping_weightzone', [
        'shipping_weightzone_status'     => 0,
        'shipping_weightzone_sort_order' => 1,
    ]);
}

public function uninstall(): void {
    $this->load->model('setting/setting');
    $this->model_setting_setting->deleteSetting('shipping_weightzone');
}

Permissions for the admin screen are handled by the extension installer when the extension is installed; if you add extra routes that need their own permission, see Install, Uninstall and Permissions.

Testing the rate logic (runnable)

The engine is where bugs cost money, so test its edges: exactly on a tier limit, just over it, exactly at the free threshold, and the disabled and too-heavy cases. A tiny harness is enough; in a real project you would use PHPUnit as in Testing and Debugging Extensions.

PHP Tests for the rate engine

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-to-last test records a business decision: free shipping applies even to a parcel heavier than the largest tier. If your client wants the opposite, change the engine and the test together. Writing the decision as a test makes it visible and stops accidental changes later.

Extending the project

  • Add a handling fee per zone by adding a second cents value and adding it to the final cost.
  • Add a maximum order weight setting and return a friendly error message string instead of an empty array.
  • Cache the parsed tiers per zone in $this->cache (see Performance in Extensions).
  • Package the finished extension with the steps in Packaging, Marketplace and Upgrades.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why does the project keep the rate calculation in a class that does not use OpenCart objects?

    A pure class takes plain values and returns plain values. You can test every edge case in milliseconds, and only the thin model has to change when OpenCart does.
  2. 2. A parcel weighs exactly 5.000 kg and the tiers are 1:4.00,5:8.50,20:15.00. Which cost applies?

    Each tier means 'up to and including this weight', so a parcel exactly on the 5 kg limit still falls in the 5 kg tier.
  3. 3. What should the engine return when the parcel is heavier than the largest tier and no free rule applies?

    null means the method cannot ship this parcel. Returning 0 would give the item away, and silently reusing the last tier would undercharge.
  4. 4. Which line in the save() method protects the settings from unauthorised changes?

    The permission check decides who may save. Validation protects data quality, but only the permission check stops a user without modify access.

Summary

  • Split the extension: a thin model that talks to OpenCart, and a pure rate engine that only does arithmetic.
  • Tiers use up to weight : cost, in ascending order, and the first matching tier wins; boundaries are inclusive.
  • A free-over rule is checked first, and "cannot ship" is null, never 0.
  • The model matches the address to geo zones, builds integer cents, and returns the quote array shape.
  • The admin controller checks permission, validates every rates field, and saves with the settings model.
  • Tests for tier edges and the free threshold document the business rules.

Next: Project: A Hosted-Checkout Payment Extension