Skip to content
Tutorials Center
My learning

Topics

Lesson 5 of 27 ยท MVC-L core

Models, the Registry and the Database

Learn how OpenCart 4 models work: loading with $this->load->model, the registry, $this->db->query and escape, DB_PREFIX, store_id and language_id, with a runnable mini model.

Controllers decide what should happen; models do the database work. In OpenCart a model is a class with methods such as getProduct() or addMessage(), and every query in the system lives in one. Keeping SQL out of controllers makes pages easier to read, lets different parts of the shop reuse the same query, and gives the event system a place to hook in.

This lesson explains how to load a model, how the registry gives it a database connection, and how to write queries that are correct and safe: the table prefix, the escape function, integer casts, and the two filters (store_id and language_id) that most catalog queries need. The real code is read-only; a small model layer on SQLite lets you run the same patterns.

Loading and calling a model

Models live beside controllers: catalog/model/... or admin/model/..., or inside your extension folder. You load one by its route, and it becomes a property of the controller, with the route turned into a property name:

PHP
$this->load->model('extension/acme/module/hello_banner');

$messages = $this->model_extension_acme_module_hello_banner->getMessages();

The property name is model_ plus the route with slashes replaced by underscores. That is long, but it is predictable. The model class itself looks like this:

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

class HelloBanner extends \Opencart\System\Engine\Model {
    public function getMessages(): array {
        $query = $this->db->query(
            "SELECT * FROM `" . DB_PREFIX . "hello_message`"
            . " WHERE `store_id` = '" . (int)$this->config->get('config_store_id') . "'"
            . " AND `language_id` = '" . (int)$this->config->get('config_language_id') . "'"
            . " ORDER BY `sort_order` ASC"
        );

        return $query->rows;
    }

    public function addMessage(string $text, int $sortOrder): int {
        $this->db->query(
            "INSERT INTO `" . DB_PREFIX . "hello_message` SET"
            . " `message` = '" . $this->db->escape($text) . "',"
            . " `sort_order` = '" . (int)$sortOrder . "'"
        );

        return $this->db->getLastId();
    }
}

Read it slowly, because every part shows a habit:

  • The model extends Opencart\System\Engine\Model. Like the controller it reaches $this->db and $this->config through the registry.
  • Table names are always DB_PREFIX . 'name', in backticks.
  • Text from outside goes through $this->db->escape(). Numbers go through a cast such as (int). This is the whole defence against SQL injection in this API, so no input may skip both.
  • query() returns an object. ->row is the first row as an array, ->rows is every row, and ->num_rows is the count. After an INSERT, getLastId() returns the new primary key, and countAffected() tells you how many rows an UPDATE or DELETE changed.

OpenCart's db->query() takes a finished SQL string. It has no placeholders, so safety depends entirely on you escaping or casting every value. A single forgotten escape() is a vulnerability. If you cannot cast it to a number or escape it, do not put it in the query.

The registry gives models their tools

You met the registry in the first lesson. Here is why it matters for models: a model has no constructor of its own. The base class stores the registry and exposes its items through __get, so $this->db is the same database object the controller sees. The practical consequences are:

  1. There is one connection per request. Models do not open their own.
  2. Anything registered by the framework (config, session, cache, log, event) is available to a model with no extra code.
  3. A model is easy to misuse as a dumping ground. Keep models about data; leave request handling and HTML to controllers and views.

The loader also wraps a loaded model in a proxy. When you call a method on the proxy, OpenCart triggers events named after the model and method (for example before and after events for catalog/model/catalog/product/getProduct), so other extensions can react or change the arguments and the result. This is why you should always call models through the property ($this->model_..._getMessages()) and never create them with new: a model built by hand skips the proxy and your own code becomes invisible to events. Events covers the details.

Store and language filters

OpenCart can run several stores from one installation, and every store can offer several languages. Many tables therefore have store_id and language_id columns, and queries must filter by them or shoppers will see rows from the wrong store or in the wrong language. The current values come from config:

PHP
$storeId    = (int)$this->config->get('config_store_id');
$languageId = (int)$this->config->get('config_language_id');

Use these two lines in every catalog-facing query that reads translated or per-store data. For your own tables, decide up front whether a row is per store, per language, both or neither, and add the columns accordingly. Changing that later is a data migration.

A mini model layer you can run

The stand-in below is not OpenCart's database library. It uses SQLite, but it copies the API shape: a Db class with query(), escape() and getLastId(), a result object with row, rows and num_rows, a table prefix, and a model that builds SQL strings the same way a real OpenCart model does. Run it and read the printed SQL.

PHP A mini model layer on SQLite

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 how the apostrophe in "It's sale time" survives. The escape() call doubled it inside the SQL so it stayed text. Without that call the statement would be invalid, or worse.

Why casting and escaping matter

The second stand-in shows what an unescaped value does. It builds one query the careless way and one the right way, using the same table and the same hostile input.

PHP Escape versus no escape

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.

In the careless version the condition OR '1'='1' makes the WHERE clause true for every row, and the status filter is bypassed, so the hidden product is exposed. Because of operator precedence the unfiltered rows come back. Security for Extension Developers returns to this with more patterns.

Habits for good models

  • One responsibility per method. getMessages() reads, addMessage() writes. A method named process() is a warning sign.
  • Return plain arrays or scalars, not query objects, so callers cannot depend on the database layer.
  • Whitelist sort fields. ORDER BY cannot be escaped like a value, so map user input to a fixed list of column names.
  • Use the cache for heavy reads, with a key that includes the store and language. Performance in Extensions shows how.
  • Create your tables on install and drop them on uninstall, as covered in Install, Uninstall and Permissions.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. How do you reach the model loaded with $this->load->model('extension/acme/module/hello_banner')?

    The property is model_ plus the route with slashes replaced by underscores.
  2. 2. Which of these is the correct way to put a user-supplied string into a query?

    db->query() takes a finished string, so you must escape text values yourself and cast numbers.
  3. 3. Why should you not create a model with new?

    The loader wraps models in a proxy that triggers events. A hand-made instance skips that.
  4. 4. Which two columns do most catalog queries need to filter on?

    Multi-store and multi-language setups store separate rows, so queries must select the current store and language.

Summary

  • Models hold the SQL. Load them with $this->load->model(route) and call them through the model_... property.
  • The registry supplies $this->db, $this->config and the rest; the loader wraps models in an event-aware proxy.
  • Always build table names with DB_PREFIX, escape text with $this->db->escape() and cast numbers.
  • query() returns row, rows and num_rows; use getLastId() and countAffected() after writes.
  • Filter by store_id and language_id where data is per store or per language.

Next: Twig Views and Language Files