Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Contents

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:

LetterPartJobFolder
MModelQueries to the databasemodel
VViewHTML template in Twigview/template
CControllerReceives the request, collects data, returns the responsecontroller
LLanguageTexts of the page for each languagelanguage

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.

ObjectWhat it is for
$this->requestRequest data: get, post, cookie, files, server
$this->responseThe response: output, headers, redirect
$this->loadLoading models, templates, language files, other controllers
$this->dbDatabase queries
$this->configShop settings
$this->sessionSession data
$this->urlBuilding links
$this->languageTexts of the loaded language files
$this->documentPage title, styles and scripts
$this->cache, $this->logCache and the error log
$this->cart, $this->customerCart and customer — storefront only
$this->userStaff 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

WhatVersion 3Version 4
Class namesControllerProductProductNamespace Opencart\Catalog\Controller\Product and class Product
Extension filesScattered across admin and catalogOne folder extension/acme_hello/
Method in the addressproduct/product/reviewproduct/product.review
Changing the coreOCMOD filesEvents first, OCMOD as a last resort
PHP78.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.

Thanks for reading!

Donate to the site — we work hard for you.