No results found

Try a different search query

Popular searches:

Add to Cart

Cart

You have no purchases yet

Browse Marketplace
Original Subtotal:
Product discounts:
Quantity Discount:
Total:
View Cart
Architecture and files

OpenCart Registry: How Objects Reach the Controller

How the OpenCart 3.0 and 4.x registry works: where $this->db, $this->config and models come from in a controller, how to add your own object, and which pitfalls to avoid.

10 min read OCTemplates OC 3.0 OC 4.x

Registry in OpenCart is a simple object registry: an associative array "key → object" that is created at the start of each request and passed to all controllers, models, and libraries. When you write $this->db, $this->config, or $this->model_catalog_product, the controller stores nothing itself: the magic method __get takes the object from the registry. Below we look at how the OpenCart registry is built in versions 3.0 and 4.x, who fills it, and how to safely add your own service to it.

What is the Registry and why does OpenCart need it?

OpenCart has no DI container like Symfony or Laravel. Instead, there is a single class Registry in the file system/engine/registry.php. It is a service locator in its simplest form: a private array $data and four or five access methods. There is no automatic dependency assembly, no factories, and no lazy services. What you put under a key is what you get back.

This is done for simplicity. Controllers and models don't need constructors with a dozen parameters: each one receives a single registry object and sees the whole core through it. The price of this simplicity is global state within a request. Any code can overwrite any key, and nothing protects against it.

Here is the entire class logic in OpenCart 4.x, without PHPDoc comments:

system/engine/registry.php · OpenCart 4.1.0.4 · lines 15–19

class Registry {
	/**
	 * @var array<string, object>
	 */
	private array $data = [];

system/engine/registry.php · OpenCart 4.1.0.4 · lines 68–82

	public function get(string $key): ?object {
		return $this->data[$key] ?? null;
	}

	/**
	 * Set
	 *
	 * @param string $key
	 * @param object $value
	 *
	 * @return void
	 */
	public function set(string $key, object $value): void {
		$this->data[$key] = $value;
	}

Three practical points follow from this code. First, the registry lives for one request only: nothing persists between requests; for that there are sessions and cache. Second, in 4.x you can only store objects, because the parameter type is object. Third, if a key is missing, get() returns null, and the error appears only when the method is called.

How does $this->db "appear" in a controller?

The base classes Controller and Model (directory system/engine/) receive the registry in the constructor and store it in the property $this->registry. They also have the magic methods __get and __set, which delegate access to the registry. So the chain for $this->db->query(...) looks like this:

  1. PHP does not find a declared property db in your controller.
  2. Controller::__get('db') is called.
  3. It accesses $this->registry->get('db').
  4. The registry returns the object DB created at the start of the request, and query() is called on it.

The registry itself also has __get, so the entries $this->registry->get('config') and $this->registry->config are equivalent:

system/engine/registry.php · OpenCart 4.1.0.4 · lines 30–32

	public function __get(string $key): ?object {
		return $this->get($key);
	}

Models get into the registry through the Loader. When you call $this->load->model('catalog/product'), the Loader creates the model object, wraps it in an event proxy, and stores it in the registry under the key model_catalog_product: slashes are replaced with underscores, and the prefix model_ is added at the beginning. In 4.x, the route for extension models is longer, so the key is too: extension/opencart/total/coupon becomes $this->model_extension_opencart_total_coupon. The Loader will be covered in detail in a separate article in this section. The key point here: a model becomes available to any code that runs later in the same request, even if that code did not load it itself.

Who fills the registry and when?

The registry is created in system/framework.php. The full request path is described in the article about framework.php and the route from index.php to the controller. Below is only what concerns the registry.

flowchart TD
  A["index.php"] --> B["system/startup.php: autoload"]
  B --> C["framework.php: new Registry()"]
  C --> D["config, log, event, load, request, response, db, session, cache…"]
  D --> E["startup controllers: setting, customer, currency, tax, cart…"]
  E --> F["Route controller"]
  F --> G["$this->load->model(): model_* in registry"]

Filling happens in two stages.

Stage 1: the core in framework.php

This is where the infrastructure objects are created: config, log, event, load, request, response, db, session, cache, url, language, document. The set and order differ somewhat between versions and between admin and catalog. Values for config are taken from file configs and then supplemented with settings from the setting table. How these layers overlap is explained in the article about config.php, system/config and database settings.

Stage 2: startup controllers

Next, controllers from the directory controller/startup/ are executed, and it is they that register the "business" objects.

OpenCart 3.0: most objects are registered in a single file catalog/controller/startup/startup.php. There, customer, currency, tax, weight, length, cart, encryption, and others are created. The list of startup actions is defined in system/config/catalog.php and admin.php.

OpenCart 4.x: startup is split into separate controllers (startup/customer, startup/currency, startup/tax, and others). In addition to the file list, there is a table startup in the database. Through it, extensions add their own startup actions without changing the core. These entries are visible in the admin on the Startup page.

List of startup actions: each row is a controller that runs before the main route and may register objects
List of startup actions: each row is a controller that runs before the main route and may register objects · OpenCart 4.1.0.4

This gives a rule: in the startup controller of your extension, you cannot yet rely on objects registered by a startup that runs later. If your service depends on customer or cart, check them via has() or register the service lazily, at the moment of first use.

How does the Registry in OpenCart 3.0 differ from 4.x?

The public interface is almost the same, but the typing is different, and this affects module compatibility. Here is the class in 3.0.5.1:

system/engine/registry.php · OpenCart 3.0.5.1 · lines 37–38

final class Registry {
	private $data = array();
AspectOpenCart 3.0OpenCart 4.x
NamespaceGlobal, class RegistryOpencart\System\Engine\Registry
Class modifierfinal, cannot be inheritedNo final
Value type in set()Any (mixed)Objects only (object)
Magic __getPresent, returns ?objectPresent, returns ?object
__set / __isset on the registry itselfNoYes
Removing a keyNo methodunset($key)

The main trap in 3.0: set() accepts a string or an array, but __get is declared with the return type ?object. So $this->registry->set('my_flag', true) works, while reading $this->my_flag through magic access ends with TypeError. An explicit $this->registry->get('my_flag') returns the value without error. Because of this inconsistency, it is better not to store scalars in the registry at all, even in 3.0. In 4.x the error will appear already at set().

The location of the class itself and neighboring core files is shown in the directory map of OpenCart 3.0 and 4.x.

How do you add your own object to the registry?

A typical task: a module has a client for an external API (delivery service, fiscal device, CRM), and it is needed in several controllers and models. Creating it anew each time is inefficient, and passing it through parameters is inconvenient. The registry is well suited for this.

OpenCart 3.0

  1. Place the class in system/library/. The 3.0 autoloader converts the namespace to a lowercase path: \Mystock\Client will be looked up as system/library/mystock/client.php.
  2. Register the object lazily, at the place where it is first needed. You can also do this in an event handler that fires at the start of the route.
  3. Use a key with your module's prefix to avoid conflicts with the core.
class ControllerExtensionModuleMystock extends Controller {
	public function index() {
		if (!$this->registry->has('mystock_client')) {
			$this->registry->set('mystock_client', new \Mystock\Client(
				$this->config->get('module_mystock_api_key'),
				$this->log
			));
		}

		$data['items'] = $this->mystock_client->getItems();

		return $this->load->view('extension/module/mystock', $data);
	}
}

OpenCart 4.x

In 4.x, the extension code lives in extension/<код_розширення>/, and the library is in extension/<код>/system/library/. The namespace is formed from the extension code: for mystock it is Opencart\Extension\Mystock\System\Library. The approach itself is the same:

namespace Opencart\Catalog\Controller\Extension\Mystock\Module;

class Mystock extends \Opencart\System\Engine\Controller {
	public function index(): string {
		if (!$this->registry->has('mystock_client')) {
			$this->registry->set('mystock_client', new \Opencart\Extension\Mystock\System\Library\Client(
				(string)$this->config->get('module_mystock_api_key'),
				$this->log
			));
		}

		$data['items'] = $this->mystock_client->getItems();

		return $this->load->view('extension/mystock/module/mystock', $data);
	}
}

If the object must be available on every request before the main controller, in 4.x there is an extension startup entry for this, which is added during module installation. Another option is an event, which can be reviewed in the section Extensions → Events.

List of events: shows which extension handlers fire and on which triggers
List of events: shows which extension handlers fire and on which triggers · OpenCart 4.1.0.4

What registry errors occur most often?

Most problems with third-party modules that "break the store after installation" come down to a few recurring situations:

  • Overwriting a service key. A module makes set('cart', ...) or set('customer', ...) its own class, and then the whole checkout works with someone else's object. Before registering, check has(), and name keys with a prefix.
  • Undeclared property in a controller. The base controller's magic __set writes to the registry, so $this->error = [] without a declared private $error = []; in 3.0 ends up in the global registry and breaks on read. In 4.x it fails immediately, because only objects are accepted. Always declare service properties of the class explicitly.
  • "Call to a member function … on null". The key is missing: the model was not loaded, startup has not finished yet, or you are accessing in admin an object that is registered only in catalog (and vice versa). Admin and catalog have separate registries, because they are two different applications.
  • Trying to keep state between requests. The registry is reset on every HTTP request, including AJAX. Store cart or filter data in the session or cache.
  • Global global $registry in templates or helpers. In 4.x a variable in the global scope may be absent, and this approach ties the code to the initialization order. Pass the registry explicitly through the constructor.

For diagnostics, it is useful to temporarily output the list of keys, for example array_keys via Reflection in debug mode, or simply check $this->registry->has('ключ') at the needed point and write the result to $this->log->write(). The log will appear in System → Maintenance → Error Logs.

Summary

  • The registry is an array of objects for one request. Controllers and models access it through the magic __get, so $this->db works without any declarations.
  • The core fills the registry in framework.php, business objects are added by startup controllers, and models are added by the Loader under keys model_*.
  • OpenCart 3.0: final, no typing, but __get expects an object. OpenCart 4.x: namespace, strict object type, and there are unset() and __isset.
  • Register your own services lazily, with a prefix in the key and a has() check. Do not put scalars or arrays into the registry.

Next, it is worth understanding how the Loader creates models and event proxies, and how Request and Response are built. The rest of the material on the internal structure of the core is collected in the section "Architecture and Files". If any term in the article is unfamiliar, check the glossary of OpenCart and e-commerce terms.

FAQ

Can I get the registry inside my own library class, not just a controller?
Yes, pass it to the constructor when creating the object: new MyClass($this->registry). This is how the core does it with the Cart, Customer and Tax classes, which receive the registry as a parameter.
Is the registry shared across stores in a multi-store setup?
Each request gets its own registry, and the settings of a specific store are loaded into config by store_id during startup. So objects from one store do not 'leak' into another.
How is $this->registry->get('x') different from $this->x in a controller?
The result is the same, because $this->x goes through __get, which calls the same get(). The explicit call is handy when the key is built dynamically or when you need to bypass magic access for debugging.
Is it safe to call $this->registry->unset() in 4.x?
Technically yes, but removing a key that the core or another module uses will break further code in this request. Only remove your own keys, and only if you really need to free the resource.
Why is a model available in the controller when I never loaded it?
Another controller or startup has already loaded it earlier in the same request, and it stayed in the registry. Don't rely on this: explicitly call $this->load->model() wherever the model is needed.
Was this article helpful?
Thanks for your feedback!

Related articles

Didn't find the answer?

Ask the community: OpenCart developers answer on the forum.

Ask on the forum
We use cookies

We use cookies and similar technologies to improve your experience, analyse traffic, and show personalised ads. Read our Cookie Policy for details.