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
MVC-L: controllers, models, templates

OpenCart route= routing: how the core finds the controller in 3.0 and 4.1

How OpenCart maps the route= parameter to a controller file, class and method, how routing differs in 3.0 and 4.1, and why modules 404 after migration.

12 min read OC 3.0 OC 4.1

OpenCartA free open-source CMS for online stores, written in PHP with a MySQL/MariaDB database. Everything that is not part of the core is added through extensions. More in the glossary → has no routing table. The route= string from the URL goes straight to a controllerCode that receives a request and prepares data. More in the glossary → file path and a method name. The scheme is the same in both branches, but the parsing rules differ. OpenCart 3.0 looks for a file by dropping segments after slashes, one at a time. OpenCart 4.1 splits off the method after a dot and loads the class from a namespace. Anyone who understands how the opencart route works finds the cause of "why is this 404" faster and moves modules between versions more easily. The examples are for OpenCart 4.1; in 4.0.x, model triggers and event handling differ.

What is route= and where does it appear in the request?

Every store or admin page is opened through index.php. The route parameter in the GET request tells the core which controller to call:

  • index.php?route=product/product&product_id=42 opens a product pageThe page for a single product: photos, price, options, description, reviews. More in the glossary →, file catalog/controller/product/product.php, method index();
  • index.php?route=checkout/cart opens the cart;
  • admin/index.php?route=catalog/product&user_token=… opens the product list in the admin.

If route is not passed, the default route from the application configuration is used. For the storefrontWhat the customer sees: the home page, categories, product page, and cart. More in the glossary →, this is the home page common/home. Where these values come from is described in the article about file configs and system/config.

When SEO URLs are enabled, "pretty" addresses such as /noutbuky/lenovo-ideapad do not contain the route parameter. The SEO URL startup controller parses the address against the seo_url table before dispatch and writes the required $this->request->get, route and product_id itself. For the router, such a request is no different from a regular index.php?route=…. A separate article about SEO addresses covers this in detail. The key point here: all roads lead to the route string.

The storefront and the admin are routed independently. Each has its own DIR_APPLICATION and its own controller/ directory, so route=common/home in admin/ and in the root leads to different files. There is an article about this split: admin and catalog as two applications on one core.

How does a request get from index.php to a controller method?

The full request path is covered in the article about framework.php and the request lifecycle. Here is only the part relevant to routing:

  1. framework.php creates the registry, config, Request, Response, session and other services.
  2. Pre-actions run, that is, startup controllers: store settings, language, currency, SEO URL, admin login check, and so on. Each of them can replace the action that will be executed next.
  3. The route value is taken from GET or from action_default.
  4. …/before events for this route are triggered.
  5. An Action object is created, which determines the file, class and method, and then calls them.
  6. If the method returned a new Action, that one is executed (internal forward). If it returned Exception, the error action is executed; for the storefront, this is error/not_found.
flowchart TD
  A["index.php"] --> B["framework.php: registry, config, Request"]
  B --> C["Startup / pre-action"]
  C --> D["SEO URL → request->get['route']"]
  D --> E["route or action_default"]
  E --> F["new Action(route)"]
  F --> G{"Controller and method found?"}
  G -- "yes" --> H["Call method"]
  G -- "no" --> I["Exception → error/not_found"]
  H --> J{"Returned Action?"}
  J -- "yes" --> F
  J -- "no" --> K["Response->output()"]

In OpenCart 3.0, this loop lives in a separate class Router:

system/engine/router.php · OpenCart 3.0.5.1 · lines 42–58

	public function dispatch(Action $action, Action $error) {
		$this->error = $error;

		foreach ($this->pre_action as $pre_action) {
			$result = $this->execute($pre_action);

			if ($result instanceof Action) {
				$action = $result;

				break;
			}
		}

		while ($action instanceof Action) {
			$action = $this->execute($action);
		}
	}

Note two details. A pre-action can return its own Action, and then the main action is not executed at all. This is exactly how the admin redirects an unauthenticated user to the login form. In addition, the while loop supports forward chains. Error handling triggers only once:

system/engine/router.php · OpenCart 3.0.5.1 · lines 66–82

	private function execute(Action $action) {
		$result = $action->execute($this->registry);

		if ($result instanceof Action) {
			return $result;
		} 
		
		if ($result instanceof Exception) {
			$action = $this->error;
			
			$this->error = null;
			
			return $action;
		}

		return null;
	}

After the first switch to the error action, $this->error is reset to zero. So if error/not_found itself is broken, there is no infinite loop, and the request simply ends with an empty response.

OpenCart 4.1: there is no separate Router class in the core. The same sequence (pre-action, route, Action, error handling) is implemented directly in system/framework.php. The principle has not changed.

How does OpenCart 3.0 parse the route into a file and a method?

All the logic is concentrated in the constructor of Action:

system/engine/action.php · OpenCart 3.0.5.1 · lines 26–39

		$parts = explode('/', preg_replace('/[^a-zA-Z0-9_\/]/', '', (string)$route));

		// Break apart the route
		while ($parts) {
			$file = DIR_APPLICATION . 'controller/' . implode('/', $parts) . '.php';

			if (is_file($file)) {
				$this->route = implode('/', $parts);		
				
				break;
			} else {
				$this->method = array_pop($parts);
			}
		}

The algorithm "bites off" segments from the end until it finds an existing file. Let's take route=extension/payment/mypay/callback:

  1. controller/extension/payment/mypay/callback.php is checked. There is no such file, so the method becomes callback.
  2. controller/extension/payment/mypay.php is checked. The file exists, so the controller route is defined as extension/payment/mypay.

If the file is found on the first attempt (route=product/product), the method remains index, that is, the default value from the class property. Sanitization leaves only Latin letters, digits, _ and /, so you cannot escape the directory via ../.

Next, execute() builds the class name: Controller plus the route with everything except letters and digits removed:

system/engine/action.php · OpenCart 3.0.5.1 · lines 64–65

		$file  = DIR_APPLICATION . 'controller/' . $this->route . '.php';	
		$class = 'Controller' . preg_replace('/[^a-zA-Z0-9]/', '', (string)$this->route);

For extension/module/hello_world, the core builds the string Controllerextensionmodulehelloworld. Since class names in PHP are case-insensitive, you can declare ControllerExtensionModuleHelloWorld in the code and the class will be found. However, underscores must be removed from the class name: ControllerExtensionModuleHello_World will no longer match.

<?php
// catalog/controller/extension/module/hello_world.php (OpenCart 3.0)
class ControllerExtensionModuleHelloWorld extends Controller {
	public function index() {
		// route=extension/module/hello_world
	}

	public function refresh() {
		// route=extension/module/hello_world/refresh
	}
}

Trap: a collision between a file and a method

Because the longer path is checked first, the file controller/account/order/info.php would intercept the route account/order/info, and the method info() in account/order.php would stop being called. Do not create a subdirectory with the same name as a controller file next to it if that subdirectory contains endpoint methods.

What changed in OpenCart 4.1: a dot instead of a slash

In 4.1, nobody walks the file system. The method is separated from the controller by the last dot:

system/engine/action.php · OpenCart 4.1.0.4 · lines 40–52

	public function __construct(string $route) {
		$this->route = preg_replace('/[^a-zA-Z0-9_|\/\.]/', '', $route);

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

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

This gives the new form of routes:

  • route=checkout/cart.add: controller checkout/cart, method add;
  • route=catalog/product.form in the admin: the product form (in 3.0 it was catalog/product/edit);
  • route=catalog/product.save: saving via AJAX.

In 4.1, the method separator is a dot. The core automatically replaces the old | separator with ., so the regular expression still accepts it. For new code, use the dot.

Another nuance is visible in the code: the cleaned string is stored only as id, and controller and method are cut from the original $route. The framework cleans the route from GET earlier. But if you build new \Opencart\System\Engine\Action(...) from user data yourself, sanitize the string on your own.

The call itself in 4.1 uses a factory and the registry:

system/engine/action.php · OpenCart 4.1.0.4 · lines 77–99

		// Create a new key to store the model object
		$key = 'fallback_controller_' . str_replace('/', '_', $this->controller);

		if (!$registry->has($key)) {
			$object = $registry->get('factory')->controller($this->controller);
		} else {
			$object = $registry->get($key);
		}

		if ($object instanceof \Opencart\System\Engine\Controller) {
			$registry->set($key, $object);
		} else {
			// If action cannot be executed, we return an error object.
			return new \Exception('Error: Could not load controller ' . $this->route . '!');
		}

		$callable = [$object, $this->method];

		if (is_callable($callable)) {
			return $callable(...$args);
		} else {
			return new \Exception('Error: Could not call controller ' . $this->route . '!');
		}

The factory turns the route into a class in a namespace, for example product/product into Opencart\Catalog\Controller\Product\Product. The underscore becomes CamelCase, so the file hello_world.php contains the class HelloWorld. The file is loaded by the autoloader based on the namespace. The controller instance is cached in the registry under the key fallback_controller_…, and repeated calls to the same controller within a request do not create a new object. For how objects get into the registry, read the article Registry in OpenCart.

How are extensions routed?

ExtensionsAdditional functionality: a module, a payment or shipping method, a feed, or a theme. They are managed in "Extensions → Extensions." More in the glossary → most often break precisely on routes, because the directory structure differs greatly between versions (see the OpenCart 3.0 and 4.1 directory map).

OpenCart 3.0: extension controllers live inside the application, in catalog/controller/extension/{тип}/{назва}.php and admin/controller/extension/{тип}/{назва}.php. The route looks like extension/module/hello_world. Apart from the extension/ prefix there is nothing special; the same file lookup applies.

OpenCart 4.1: each extension lives in a separate extension/{код_розширення}/ directory with subdirectories admin/ and catalog/. The route contains the extension code: extension/opencart/module/featured for the built-in "Featured" module. For installed extensions, the core registers in the autoloader a namespace of the form Opencart\Catalog\Controller\Extension\{Код} bound to extension/{код}/catalog/controller/, so the class must match this namespace:

<?php
// extension/my_shop/catalog/controller/module/hello_world.php (OpenCart 4.1)
namespace Opencart\Catalog\Controller\Extension\MyShop\Module;

class HelloWorld extends \Opencart\System\Engine\Controller {
	public function index(): string {
		// route=extension/my_shop/module/hello_world
		return '';
	}

	public function refresh(): void {
		// route=extension/my_shop/module/hello_world.refresh
	}
}

If the namespace in the file does not match what the factory expects, you get "Could not load controller" and a 404 page. Most often this is a case error or forgotten CamelCase for a code with an underscore.

Extension routes also use events and startup records. In the 4.1 admin, the list of startup actions that run before the main route can be viewed in the "Extensions → Startup" section:

List of startup records: code, action route and status
List of startup records: code, action route and status · OpenCart 4.1.0.4

Subscriptions to …/before and …/after of specific routes are shown in the "Extensions → Events" section. When a page behaves strangely, first check whether its route is being intercepted by another module:

Events: trigger with a controller route and the action subscribed to it
Events: trigger with a controller route and the action subscribed to it · OpenCart 4.1.0.4

3.0 vs 4.1: comparison and common migration mistakes

AspectOpenCart 3.0OpenCart 4.1
Method separator/ (last segment, if there is no such file). (in early 4.0.x — |)
Controller lookupWalking is_file() with segments droppedFactory + autoloader by namespace
Class nameControllerProductProductOpencart\Catalog\Controller\Product\Product
Method checkReflection: the method exists, no more required parameters than argumentsis_callable()
DispatcherClass RouterLogic in system/framework.php
Extension pathextension/module/xextension/{код}/module/x

When migrating a module from 3.0 to 4.1, the following mistakes occur most often:

  • A slash instead of a dot. route=extension/my_shop/module/hello_world/refresh in 4.1 looks for the controller …/hello_world/refresh. It is not found, and you get a 404.
  • Hardcoded URLs in JS. It is better to generate links to AJAX endpoints in the controller via $this->url->link() and pass them to the template, rather than assembling the string in JavaScript.
  • Required method parameters. In 3.0, a method with a required argument cannot be called directly from a URL: Reflection notices that arguments are missing. Such a method is available only via load->controller() with arguments. How this works is described in the article about Loader and load->controller.
  • Public helper methods. In both 3.0 and 4.1, any public controller method (except those starting with __) can be called from a browser. Put helper logic into private/protected, and in the admin, check permissions and user_token in every endpoint.

If a "Page not found" message appears instead of the page, enable error display and logging in "System → Settings" (System → Settings), on the "Server" tab. Check the log and search it for the exception text from Action:

Server tab: SEO URL, error display and logging
Server tab: SEO URL, error display and logging · OpenCart 4.1.0.4

Keep in mind that Exception returned from Action is not logged by the router: it simply moves on to error/not_found. So an empty log on a 404 usually means the route did not resolve, not that the code crashed. In that case, walk the path manually: route → file → class → method.

Never assemble index.php?route=… by concatenation. The $this->url->link() method takes into account the store domain, SSL and, most importantly, SEO URLs: if the route with parameters has a keyword, you get a "pretty" address. The admin also passes user_token through it.

// OpenCart 3.0
$data['refresh'] = $this->url->link('extension/module/hello_world/refresh', '', true);

// OpenCart 4.1
$data['refresh'] = $this->url->link('extension/my_shop/module/hello_world.refresh', 'language=' . $this->config->get('config_language'));

In 4.1, the storefront links usually get the language parameter added, because language selection and the language prefix in the SEO address depend on it. Details are described in the overview multilanguage, hreflang and language prefixes. Read request parameters from $this->request->get, not from superglobal arrays, as explained in the article Request and Response in OpenCart. If a 3.0 store needs more flexible SEO URLs and redirects from old addresses than the standard seo_url table provides, look at OCT SEO Pro. It works on top of the same route substitution mechanism.

Summary

  • route= maps directly to a file, a class and a method. There is no routing table, so there is no need, and no way, to "register" a route.
  • OpenCart 3.0: Action drops segments from the end until it finds a file, and the last dropped segment becomes the method. The class has the form Controller + the route without separators.
  • OpenCart 4.1: the method follows the last dot, the class is loaded from its namespace through the factory, and the instance is cached in the registry.
  • SEO URLs and startup controllers only substitute route before dispatch. A pre-action can replace the action entirely.
  • Any public controller method is an endpoint. Protect it with permissions and a token.

Next, it is worth looking at how the controller itself is structured: data, template and child controllers. Start with the MVC-L relationship diagram, and you will find the rest of the topics in this section on the page MVC-L: controllers, models, templates.

FAQ

Can you set a custom address in OpenCart without route=, for example /api/hello?
The core has no route configuration, so usually you add an entry to the seo_url table for the required route or write your own startup controller that parses the address and writes route into request->get. The rewrite rules in .htaccess only pass the path to index.php, and the route is determined by PHP code.
Why does route=common/home work, but route=Common/Home gives a 404 in 4.1?
In 4.1 the route is turned into a file path by the autoloader, and on Linux hosting the file system is case-sensitive. Always write routes in lowercase, as the files are named.
Can you call an admin controller from the storefront via route?
No. Each application looks for controllers only in its own controller directory, so a storefront route will never reach admin/controller. Move shared logic into a library or duplicate the controller in each application.
How do you intercept someone else's route without changing core files?
Subscribe to the event on the controller trigger of the required route with the suffix before or after. In the before handler you can change the arguments or return your own result, and in after you can change the output.
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.