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 Loader: how load->controller, model, view and language work

We break down the Loader class in OpenCart 3.0 and 4.x: how models are loaded through the proxy, nested controllers, Twig templates and language files, and where events fire in this chain.

12 min read OCTemplates OC 3.0 OC 4.x

OpenCart Loader is the system class Loader, available in every controller as $this->load. You use it to load models, call other controllers, render templates, and load language files. Almost every such call goes through the event system. If you understand what Loader does in 3.0 and 4.x, you know where $this->model_catalog_product comes from, why an event does not fire, and how to intercept someone else's call without editing the core.

What is Loader and where does $this->load in a controller come from?

The class lives in system/engine/loader.php in both branches. Its instance is created at application startup and stored in the Registry under the key load. When you write $this->load in a controller or model, the base class's magic __get retrieves the object from the registry. This mechanism is described in detail in the article about Registry and how objects get into the controller. The place of Loader in the overall request cycle is described in the article about the request path from index.php to the controller.

The main thing to remember: Loader keeps no state other than a reference to the Registry. Everything it loads (model proxies, libraries, cached controller objects in 4.x) goes back into the Registry. That is why a model loaded in one controller is also available in a nested one. And an event can replace the arguments of any call, because it receives them by reference.

In 4.x, Loader got its own __get and __set, which proxy the Registry. That is why inside the class the code simply writes $this->event, $this->factory, $this->template. In 3.0 the class is declared as final, and it accesses services through $this->registry->get('event').

MethodOpenCart 3.0OpenCart 4.x
controller($route, $data = array()), method via /(string $route, ...$args), method via . (the | symbol is replaced with .)
modelClass ModelCatalogProduct, file DIR_APPLICATION/model/...Namespaces, the object is created by factory
view($route, $data = array())(string $route, array $data = [], string $code = '')
language($route, $key = '')(string $route, string $prefix = '', string $code = '')
libraryReturns nothing, key is basename($route)Returns an object, key is library_...
configReturns nothingReturns an array

How does $this->load->model() work, and why is the model a proxy?

A call to $this->load->model('catalog/product') does not create the model right away. Loader puts an Proxy object into the Registry under the key model_catalog_product: slashes are replaced with underscores. For each public method of the class, a closure is attached to the proxy. It is this closure that, during the call, fires the before/after events and only then calls the real model method.

system/engine/loader.php · OpenCart 3.0.5.1 · lines 72–87

		if (!$this->registry->has('model_' . str_replace('/', '_', $route))) {
			$file  = DIR_APPLICATION . 'model/' . $route . '.php';
			$class = 'Model' . preg_replace('/[^a-zA-Z0-9]/', '', $route);
			
			if (is_file($file)) {
				include_once($file);
	
				$proxy = new Proxy();
				
				// Overriding models is a little harder so we have to use PHP's magic methods
				// In future version we can use runkit
				foreach (get_class_methods($class) as $method) {
					$proxy->{$method} = $this->callback($this->registry, $route . '/' . $method);
				}
				
				$this->registry->set('model_' . str_replace('/', '_', (string)$route), $proxy);

OpenCart 3.0: the class name is formed from the route, with everything except letters and digits removed. So extension/module/my_promo becomes ModelExtensionModuleMypromo, not ModelExtensionModuleMyPromo. In practice this does no harm, because class names in PHP are case-insensitive. But underscores cannot be added to a class name. The model object itself is created lazily, on the first method call, and is cached in a static variable of the closure.

OpenCart 4.x: the file and class are found via factory by namespace, for example Opencart\Catalog\Model\Catalog\Product. For extensions the route has the form extension/код_розширення/module/назва, and the file is located in extension/код_розширення/catalog/model/module/назва.php. The created object is stored in the Registry as fallback_model_..., and methods with the __ prefix do not get onto the proxy. Arguments are passed to the closure by reference (&...$args), so the before event can change the call parameters.

// Однаково працює в 3.0 і 4.x
$this->load->model('catalog/product');

$product_info = $this->model_catalog_product->getProduct($product_id);

How do you call another controller via $this->load->controller()?

Nested controllers are the foundation of page composition. The header, footer, columns, and modules in the layouts are rendered exactly this way. The main controller collects the HTML of the parts into $data and passes it to the template:

$data['column_left'] = $this->load->controller('common/column_left');
$data['footer'] = $this->load->controller('common/footer');
$data['header'] = $this->load->controller('common/header');

Calling a specific method

OpenCart 3.0: the method is specified as the last segment after a slash, for example extension/module/my_promo/getBlock. The Action class strips segments from the end until it finds the controller file. The remainder becomes the method name, and by default index is called. The $data array arrives as the first argument of the method.

OpenCart 4.x: the method is separated by a dot, extension/my_promo/module/promo.getBlock. Early 4.0 versions used |, so Loader still replaces it with a dot. There can be any number of arguments, and they are passed as variadic.

system/engine/loader.php · OpenCart 4.1.0.4 · lines 69–90

	public function controller(string $route, ...$args) {
		// Sanitize the call
		$route = preg_replace('/[^a-zA-Z0-9_|\/\.]/', '', str_replace('|', '.', $route));
		$trigger = $route;

		// Trigger the pre events
		$this->event->trigger('controller/' . $trigger . '/before', [&$route, &$args]);

		$pos = strrpos($route, '.');

		if ($pos !== false) {
			$controller = substr($route, 0, $pos);
			$method = substr($route, $pos + 1);
		} else {
			$controller = $route;
			$method = 'index';
		}

		// Stop any magical methods being called
		if (str_starts_with($method, '__')) {
			return new \Exception('Error: Calls to magic methods are not allowed!');
		}

Note two differences. First, in 4.x the controller object is cached in the Registry (fallback_controller_...). Repeated calls to the same controller within a request do not create a new instance, so properties written to $this "survive" until the next call. Second, on an error in 4.x it returns an \Exception object instead of throwing it. If you put the result straight into $data, the error text ends up directly in the page's HTML. In 3.0, in such a case, null is returned.

How does $this->load->view() render a Twig template?

The method takes the template route without an extension and an array of variables, and returns a ready HTML string. It outputs nothing itself. The output is done by $this->response->setOutput() in the main controller.

$this->response->setOutput($this->load->view('product/product', $data));

OpenCart 3.0: Loader itself creates Template with the engine from the template_engine setting, passes the variables one by one, and renders the file from the template_directory directory. In the admin this is admin/view/template/. On the storefront the active theme's directory is added to the route, so product/product becomes the theme file product/product.twig. Through the $code parameter, the before event can substitute template content for the file. This is how edits from the "Theme Editor" work.

OpenCart 4.x: rendering is delegated to the template service, and $code became an explicit method parameter.

system/engine/loader.php · OpenCart 4.1.0.4 · lines 175–195

	public function view(string $route, array $data = [], string $code = ''): string {
		// Sanitize the call
		$route = preg_replace('/[^a-zA-Z0-9_\/]/', '', $route);

		$trigger = $route;

		$output = '';

		// Trigger the pre events
		$this->event->trigger('view/' . $trigger . '/before', [&$route, &$data, &$code, &$output]);

		if (!$output) {
			// Make sure it's only the last event that returns an output if required.
			$output = $this->template->render($route, $data, $code);
		}

		// Trigger the post events
		$this->event->trigger('view/' . $trigger . '/after', [&$route, &$data, &$output]);

		return $output;
	}

Extension templates in 4.x are addressed the same way as models. The call $this->load->view('extension/my_promo/module/promo', $data) looks for the file extension/my_promo/catalog/view/template/module/promo.twig. Route sanitization removes everything except Latin letters, digits, underscores, and slashes, so a hyphen in a template file name will not work. Where templates live in each version is shown in the OpenCart directory map.

How does $this->load->language() work, and why do you need a prefix or language code?

The method loads the language file of the current language into the Language object and returns an array of strings. After that, the values are available via $this->language->get('heading_title'). The standard system event also mixes them into $data before rendering, so in Twig it is enough to write {{ heading_title }}.

$this->load->language('product/product');

$this->document->setTitle($this->language->get('heading_title'));

Files are merged into one array, so identical keys from different files overwrite each other. The most common cases are heading_title and text_success. If your module loads a language file after the main one, the page title may change unexpectedly.

OpenCart 3.0: the second parameter of $key lets you load a file into a separate namespace rather than the shared array. This is handy for pulling strings from another section without touching the current ones.

OpenCart 4.x: the signature changed to language($route, $prefix, $code). The $prefix parameter adds a prefix to the keys and solves the same conflict problem. The $code parameter loads a file of a different language. This is useful, for example, when an administrator with the Ukrainian interface sends an email to a customer who placed an order in English. Sanitization in 4.x keeps the hyphen, because language codes have the form uk-ua or en-gb.

The texts themselves can be overridden without editing files in "Design → Language Editor". Values from the database replace the strings from the file.

Language Editor: overriding a language file string without changing the code
Language Editor: overriding a language file string without changing the code · OpenCart 4.1.0.4

How do events intercept Loader calls?

Almost every Loader method has two event entry points: тип/маршрут/before and тип/маршрут/after. The type is controller, model, view, language, or config, and in 4.x also library. Arguments are passed by reference, so a handler can change the route, the data, or the result. This is the main "clean" way to extend without editing files. The alternative via XML patches is described in the article about OCMOD and edits without changing system files.

sequenceDiagram
    participant C as "Controller"
    participant P as "Model proxy"
    participant E as "Event"
    participant M as "Model object"
    C->>P: "getProduct(42)"
    P->>E: "model/.../before (args by reference)"
    P->>M: "call method"
    M-->>P: "result"
    P->>E: "model/.../after (output by reference)"
    P-->>C: "return output"

The trigger format for models differs between versions. In 3.0 the method is attached with a slash (model/catalog/product/getProduct/after), in 4.x with a dot (model/catalog/product.getProduct/after). This is the first thing to check when an event ported from 3.0 is "silent".

An even more important difference concerns how a handler replaces the result:

  • OpenCart 3.0: if the handler before returns a value (not null and not an Exception), Loader skips the real call and uses that value. A return from after likewise replaces the result.
  • OpenCart 4.x: Loader ignores the value returned by the trigger. You must change the arguments by reference: &$output in after, and for view also &$output in before to skip rendering.

Registered events are visible in "Extensions → Events". You can disable them there to check whether another handler is breaking the output.

Events list: the trigger and action columns show which Loader call is intercepted
Events list: the trigger and action columns show which Loader call is intercepted · OpenCart 4.1.0.4

What are the typical Loader errors and how do you diagnose them?

Most problems come down to a mismatch between the route, the file, and the class name. Loader silently strips invalid characters from the route, so a mistake in the path often shows up somewhere other than where you are looking.

  • "Error: Could not load model ..." — the file is missing, or (in 4.x) the class is not in the correct namespace. Check the route, the file path, and the namespace line by line.
  • "Call to a member function ... on null" — the model was not loaded in this controller, or the Registry key is different. For account/address the property is called model_account_address.
  • The text "Error: Could not call controller" directly on the page — in 4.x controller() returned an Exception, and it was output as a string. Check the result via instanceof \Exception.
  • An event does not fire after migrating from 3.0 — the trigger uses / instead of . before the method name, or the handler returns a value instead of changing the argument by reference.
  • The template is not found — a hyphen in the file name, an extra .twig in the route, or (in 3.0 on the storefront) the template is not in the active theme's directory.
  • An error about a missing class when changing settings — the language or config route is specified incorrectly. How the settings are organized is described in the article about config.php and settings in the database.

Exceptions thrown by Loader end up in the log if error logging is enabled in "System → Settings" on the "Server" tab. The log itself is opened via "System → Maintenance → Error Logs".

Error log: messages such as Could not load model or controller with the route are visible here
Error log: messages such as Could not load model or controller with the route are visible here · OpenCart 4.1.0.4

Summary

  • Loader is a thin layer between the controller and the Registry. Everything loaded is stored in the registry, and every call is wrapped in before/after events.
  • Models are proxies with closures, so model/... events work without editing model code. In 3.0 the method in the trigger is separated by /, in 4.x by ..
  • The controller method in 3.0 is specified with a slash, in 4.x with a dot. Errors in 4.x are returned as an Exception object rather than thrown.
  • In 4.x, event handlers change the result only by reference; the returned value is ignored.
  • language() in 4.x supports prefixes and loading another language. In 3.0, isolation is provided by the $key parameter.

Next, it is worth opening system/engine/loader.php of your version alongside this article and stepping through one real model call with a debugger, from the proxy to the event. The remaining topics on how the core is organized are collected in the "Architecture and files" section.

FAQ

Can you load an admin model from the storefront using $this->load->model()?
No, Loader only looks for a model within the current application: in 3.0 via DIR_APPLICATION, in 4.x via the Catalog or Admin namespace. Move the shared logic into a common library or duplicate the model on the catalog side.
Do you need to call $this->load->model() again in every controller method?
One call per request is enough, because the proxy is already stored in the Registry and available to all controllers. Calling it again is safe, so many developers add it to every method for readability.
How do I get a module's HTML from another controller to insert into my template?
Call $this->load->controller() with the module's route and pass its settings as an argument. Put the returned string into $data, then output it in Twig while keeping the HTML unescaped.
Why does the view event fire for the admin when I only wanted it on the storefront?
Events are registered with a trigger that starts with admin/ or catalog/, and this prefix defines the application. Check the trigger in the event list and, if needed, create the event with the correct prefix.
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.