Core concepts
Before writing code it helps to know five words that appear in every lesson: MVC-L, registry, extension, event and version. Each of them gets its own lessons later — here is only what they mean.
MVC-L
Every page is assembled from four files, each with one job:
| Letter | Part | Job | Folder |
|---|---|---|---|
| M | Model | Queries to the database | model |
| V | View | HTML template in Twig | view/template |
| C | Controller | Receives the request, collects data, returns the response | controller |
| L | Language | Texts of the page for each language | language |
The controller is the main one: it loads the other three.
The registry
OpenCart has no dependency injection. All shared objects are stored in one place — the registry — and are available in every controller and model as properties of $this:
// inside any controller or model method
$productId = (int) ($this->request->get['product_id'] ?? 0);
$storeName = $this->config->get('config_name');The first line reads a parameter from the address, the second reads the shop name from the settings.
| Object | What it is for |
|---|---|
$this->request | Request data: get, post, cookie, files, server |
$this->response | The response: output, headers, redirect |
$this->load | Loading models, templates, language files, other controllers |
$this->db | Database queries |
$this->config | Shop settings |
$this->session | Session data |
$this->url | Building links |
$this->language | Texts of the loaded language files |
$this->document | Page title, styles and scripts |
$this->cache, $this->log | Cache and the error log |
$this->cart, $this->customer | Cart and customer — storefront only |
$this->user | Staff member — admin panel only |
Extensions
An extension is a folder in extension/ with its own admin and catalog parts. It is installed and removed from the admin panel. Extensions have types: module, payment, shipping, total, theme and others.
Events
An event is a signal the engine sends before and after every controller, model and template call. An extension subscribes to the signal and changes data or output without editing core files.
Version 3 and version 4
| What | Version 3 | Version 4 |
|---|---|---|
| Class names | ControllerProductProduct | Namespace Opencart\Catalog\Controller\Product and class Product |
| Extension files | Scattered across admin and catalog | One folder extension/acme_hello/ |
| Method in the address | product/product/review | product/product.review |
| Changing the core | OCMOD files | Events first, OCMOD as a last resort |
| PHP | 7 | 8.0 or newer |
In releases 4.0.0 and 4.0.1 the method was separated by a vertical bar instead of a dot.
Common mistake
Objects of the registry are used outside a controller or model — in a plain function or a class of your own — and $this->db does not exist there. Registry objects are available only in classes that extend the Controller or Model class of the engine. Keep database code in models and call them from controllers.