Skip to content
Tutorials Center
My learning

Topics

Lesson 4 of 27 ยท MVC-L core

Routing and Controllers

Follow an OpenCart 4 route from index.php?route= to a controller method, learn the Action class, user_token, language and the url helper, and build a mini dispatcher.

Every page, every Ajax call and every admin form in OpenCart arrives as a route: a short string that says which controller file and which method should handle the request. A route is the address of your code, so understanding it is the first real step of extension development. Once you can predict which file a route will run, and which URL you need to call it, most of the framework stops being mysterious.

In this lesson you will read the route format, see what the Action class does with it, write controllers that return HTML or JSON, learn why the admin needs a user_token, and build links with the url helper. The real code is shown read-only. The stand-ins implement a small dispatcher so you can watch the matching rules in action.

The route format

A storefront URL looks like this:

TEXT
https://shop.test/index.php?route=product/product&language=en-gb&product_id=40

The important part is route=product/product. It has two slashes' worth of structure: the folder, the file and (optionally) the method. For core pages the route has two segments, folder/file, which maps to catalog/controller/folder/file.php. Extensions add the extension/<vendor>/ prefix and a type folder:

TEXT
extension/acme/module/hello_banner         ->  method index()
extension/acme/module/hello_banner.save    ->  method save()

When no method is named, OpenCart calls index. When one is named, it is separated from the file by a dot in the 4.0.2 line and later (earlier 4.0 releases used a pipe character). The segment before the dot is the file; everything is lowercase with underscores.

If your shop has SEO URLs enabled, shoppers see pretty paths such as /en-gb/catalog/phones. A startup action converts them back to a normal route before the router runs, so your controller code does not change. When you build links, always use the url helper and never write the paths by hand.

What the Action class does

The framework builds an Action object from the route string. In simplified terms it:

  1. Splits off the method name (after the dot, defaulting to index).
  2. Rejects any method whose name starts with two underscores. Those are private to the framework, so ?route=...__construct cannot be called from a browser.
  3. Converts the remaining path into a file path and a class name using the rules from Anatomy of an Extension.
  4. Includes the file, creates the controller with the registry, and checks that the method exists and is callable.
  5. Calls the method and passes on its return value.

If anything fails (file missing, method missing, bad name), the router falls back to an error route, which shows the not-found page. That explains the usual symptom of a typo: the shop returns "Page Not Found" and nothing in the log tells you why. Compare the route, the file path and the method name.

Before your action runs, a list of pre-actions runs first. They set up the session, load settings from the database, resolve SEO URLs, apply the language and, in the admin, check that the user is logged in and holds a valid token. Your controller can rely on that work having been done.

flowchart TD
    A["index.php?route=..."] --> B["Pre-actions<br/>(session, settings, SEO URL, login)"]
    B --> C["Action: parse route and method"]
    C -->|valid| D["Controller method"]
    C -->|invalid| E["error/not_found"]
    D --> F["Response"]

Pre-actions prepare the request, then the Action decides between your method and the not-found page.

A catalog controller

Here is a read-only storefront controller. A module returns its HTML as a string; the layout system places it on the page.

PHP
<?php
namespace Opencart\Catalog\Controller\Extension\Acme\Module;

class HelloBanner extends \Opencart\System\Engine\Controller {
    public function index(): string {
        $this->load->language('extension/acme/module/hello_banner');

        $data['heading'] = $this->language->get('heading_title');
        $data['message'] = $this->config->get('module_hello_banner_message');

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

    public function data(): void {
        $json = ['message' => $this->config->get('module_hello_banner_message')];

        $this->response->addHeader('Content-Type: application/json');
        $this->response->setOutput(json_encode($json));
    }
}

Several registry services appear here without being declared:

  • $this->load loads languages, models and views. $this->load->language() reads the language file for the given route and puts its strings into $this->language.
  • $this->config->get() reads a setting. Settings saved by an extension carry a prefix such as module_hello_banner_ (more in Admin Settings Forms).
  • $this->request->get and $this->request->post are the cleaned input arrays. Read your inputs from there, cast them to the expected type and never use $_GET directly.
  • $this->response->setOutput() sends the body; addHeader() adds an HTTP header. A method that does not return a string uses this pair to answer.

The route extension/acme/module/hello_banner.data would return the JSON from the second method. Anything public in a controller can be called from the outside, so every public method must be written as if a stranger will call it. See Security for Extension Developers.

The admin side and user_token

Admin controllers look almost the same but live under Opencart\Admin\Controller\.... The difference is the user_token. After login, the admin session holds a random token, and every admin URL must carry it as a parameter. A request without a matching token is bounced to the login page. This blocks cross-site request forgery: another website cannot guess the token, so it cannot forge your clicks.

PHP
<?php
namespace Opencart\Admin\Controller\Extension\Acme\Module;

class HelloBanner extends \Opencart\System\Engine\Controller {
    public function index(): void {
        $this->load->language('extension/acme/module/hello_banner');
        $this->document->setTitle($this->language->get('heading_title'));

        $data['save'] = $this->url->link(
            'extension/acme/module/hello_banner.save',
            'user_token=' . $this->session->data['user_token']
        );

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

        $this->response->setOutput($this->load->view('extension/acme/module/hello_banner', $data));
    }

    public function save(): void {
        $json = [];

        if (!$this->user->hasPermission('modify', 'extension/acme/module/hello_banner')) {
            $json['error'] = 'Permission denied';
        }

        $this->response->addHeader('Content-Type: application/json');
        $this->response->setOutput(json_encode($json));
    }
}

Two checks are separate. The token proves the request came from a logged-in browser session. The permission check (hasPermission('modify', $route)) proves that this particular admin user is allowed to change this extension. Pages that change data need both. The token is added to links by you; the permission is checked by you too, in every method that writes.

Never concatenate URLs by hand. $this->url->link($route, $args) builds a correct link: it adds index.php?route=, URL-encodes where needed, and applies SEO URL rules in the storefront. In the storefront you add the language argument because every storefront URL carries it in 4.x:

PHP
$link = $this->url->link(
    'product/product',
    'language=' . $this->config->get('config_language') . '&product_id=' . (int)$product_id
);

For admin links, pass user_token=... instead. Forgetting the token is the most common reason an admin button "does nothing" or throws you back to the login page.

A route dispatcher you can run

The stand-in below mimics the Action logic in miniature. It parses folder/file.method, refuses methods starting with two underscores, defaults to index, calls the controller with a registry and returns a not-found response for any failure. Change the route strings at the bottom and watch what happens.

PHP A route dispatcher with a registry

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The real Action class does more (it triggers events around the call and reports file and class errors separately), but the matching rules are the same.

A url helper you can run

The second stand-in builds links the way the helper does: a route, extra parameters, and the two mandatory extras. It shows why centralising link building prevents mistakes.

PHP A tiny url helper

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. In the 4.0.2 line and later, which route calls the save() method of the module file hello_banner?

    The method comes after a dot at the end of the route. Without it the Action calls index().
  2. 2. What does the user_token protect against?

    Only the logged-in admin session knows the token, so a foreign site cannot forge admin requests.
  3. 3. Why can a browser not call a controller method named __construct through the route?

    Methods starting with two underscores are treated as framework-internal and rejected.
  4. 4. Which is the correct way to build an admin link in a controller?

    The url helper builds a correct link, and the admin needs the token on every URL.
  5. 5. A token check alone is enough to let a user change extension settings.

    The token proves the session. The permission check proves this user may modify this extension.

Summary

  • A route is folder/file or extension/vendor/type/file, with an optional .method; the default method is index.
  • The Action class parses the route, rejects __ methods, loads the controller and calls the method; failures fall back to the not-found page.
  • Controllers reach services through the registry ($this->load, $this->config, $this->request, $this->response).
  • Admin URLs need user_token, and writes need a hasPermission check too.
  • Build every link with $this->url->link(), adding language in the storefront.

Next: Models, the Registry and the Database