Skip to content
Tutorials Center
My learning

Topics

Lesson 10 of 30 ยท Front Office

Module Front Controllers

Build your own storefront pages and AJAX endpoints with ModuleFrontController: file layout, friendly URLs, initContent, JSON responses, redirects and tokens.

Hooks let a module add pieces to existing pages. But sometimes you need a whole new page or an endpoint of your own: a wishlist page, an "add to wishlist" AJAX call, a callback that a payment provider requests. For that, a module ships a front controller: a class that handles one URL on the storefront.

In this lesson you learn where the file goes, what the class is called, how a request flows through it, how to answer with a page, JSON or a redirect, how URLs (including friendly ones) are generated, and how tokens protect actions. You should know what a module looks like and how a hook method returns HTML (Common Front Office Hooks).

Real controllers need a running PrestaShop and cannot run on this site, so they appear as read-only code. The live TryIts are PHP stand-ins that model the router and the request lifecycle; they are not PrestaShop code.

File, class and URL

A front controller is a file in controllers/front/ inside the module. The file name (without .php) is the controller name, and it is lowercase.

TEXT
modules/acmewishlist/
  acmewishlist.php
  controllers/
    front/
      toggle.php        -> controller "toggle"
      mylist.php        -> controller "mylist"
  views/templates/front/
    mylist.tpl

The class name is the module name with its first letter capitalized, then the controller name with its first letter capitalized, then ModuleFrontController:

PHP
<?php
// modules/acmewishlist/controllers/front/mylist.php (read-only)
class AcmewishlistMylistModuleFrontController extends ModuleFrontController
{
    public function initContent(): void
    {
        parent::initContent();

        $this->context->smarty->assign('items', []);
        $this->setTemplate('module:acmewishlist/views/templates/front/mylist.tpl');
    }
}

The two basic calls are parent::initContent() (it prepares the page context: the layout, the cart, the customer) and $this->setTemplate(), which picks the Smarty template. The module: prefix means "look in that module, and let the theme override it" (Smarty Templates and Theme Integration).

Without friendly URLs, the page is reached with query parameters:

TEXT
https://shop.example/index.php?fc=module&module=acmewishlist&controller=mylist

With friendly URLs enabled, the same page is available as /module/acmewishlist/mylist. In code, never write these by hand. Ask the link builder:

PHP
<?php
// read-only
$url = $this->context->link->getModuleLink(
    'acmewishlist',            // module name
    'toggle',                  // controller name
    ['id_product' => 42],      // extra query parameters
    true                       // secure (https) if the shop supports it
);

getModuleLink() returns whichever form the shop is configured for, including the language and shop prefix when needed.

Custom routes and friendly URLs

/module/acmewishlist/mylist works but is not pretty. A module can register its own rule through the moduleRoutes hook. The module registers that hook in install() and returns a list of routes:

PHP
<?php
// read-only
public function hookModuleRoutes(array $params): array
{
    return [
        'module-acmewishlist-list' => [
            'controller' => 'mylist',
            'rule' => 'wishlist',
            'keywords' => [],
            'params' => [
                'fc' => 'module',
                'module' => 'acmewishlist',
            ],
        ],
        'module-acmewishlist-item' => [
            'controller' => 'item',
            'rule' => 'wishlist/{id}-{rewrite}',
            'keywords' => [
                'id' => ['regexp' => '[0-9]+', 'param' => 'id'],
                'rewrite' => ['regexp' => '[_a-zA-Z0-9\pL-]*'],
            ],
            'params' => [
                'fc' => 'module',
                'module' => 'acmewishlist',
            ],
        ],
    ];
}
  • rule is the URL pattern. Parts in braces are keywords.
  • keywords gives each keyword a regular expression and the request parameter it fills (param).
  • params must contain fc => module and the module name so the dispatcher sends the request to your controller.
  • The route id (module-acmewishlist-list) must be unique in the shop.

Routes are read when the dispatcher builds its table, which is cached, so clear the cache after changing them. To build the URL, pass the route id to the link builder: $this->context->link->getModuleLink('acmewishlist', 'mylist') uses the matching route when one exists.

Stand-in: a router

This first stand-in is a model of the dispatcher: it compiles rules with keywords into regular expressions, matches request paths, falls back to the query-string form, and builds links in both styles. The names echo the real ones, but the code is ours.

PHP Stand-in: friendly URL router

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 last request, /wishlist/abc-nope, does not match because abc is not digits: the keyword regular expression is what keeps the route precise. In a shop this ends in the 404 page.

The request lifecycle

When the dispatcher has chosen your controller, it creates the object and calls run(). In very rough terms this is what happens, in order:

  1. init() sets up the context (customer, cart, language, currency) and checks access.
  2. postProcess() handles submitted data and actions.
  3. For an AJAX request, displayAjax() runs and sends the response. Otherwise initContent() prepares the page, and display() renders the template inside the theme layout.

The common properties and methods you work with:

Member Purpose
$this->context the current customer, cart, language, shop, link, smarty
$this->auth = true the visitor must be logged in; guests are redirected to the login page
$this->ajax = true treat the request as AJAX and call displayAjax()
postProcess() process form submissions and actions
initContent() assign data and choose the template
setTemplate() choose the Smarty template
$this->errors, $this->success messages shown in the page's notification area
flowchart TD
    A["Dispatcher finds module controller"] --> B["init: context, access"]
    B --> C{"auth required<br/>and guest?"}
    C -->|"yes"| D["Redirect to login"]
    C -->|"no"| E["postProcess: handle input"]
    E --> F{"AJAX request?"}
    F -->|"yes"| G["displayAjax: JSON out"]
    F -->|"no"| H["initContent: assign and setTemplate"]
    H --> I["display: template in theme layout"]

Each controller runs through the same stages; you override only the stages you need.

Answering with JSON

An endpoint for JavaScript returns data instead of a page:

PHP
<?php
// modules/acmewishlist/controllers/front/toggle.php (read-only)
class AcmewishlistToggleModuleFrontController extends ModuleFrontController
{
    public $auth = true;  // guests are sent to the login page
    public $ajax = true;

    public function displayAjax(): void
    {
        $token = (string) Tools::getValue('token');
        if (!hash_equals(Tools::getToken(false), $token)) {
            http_response_code(403);
            $this->ajaxRender(json_encode(['ok' => false, 'error' => 'bad_token']));
            return;
        }

        $idProduct = (int) Tools::getValue('id_product');
        // ... add or remove the product for $this->context->customer->id ...

        header('Content-Type: application/json');
        $this->ajaxRender(json_encode(['ok' => true, 'id_product' => $idProduct]));
    }
}

Points to notice:

  • Tools::getValue() reads $_POST and $_GET. Cast numbers right away with (int).
  • $this->ajaxRender() outputs the body and ends the request (it replaced the older ajaxDie() in newer versions). Always send a content type and an HTTP status that matches the result.
  • Keep AJAX controllers cheap: they are called often and the whole context is built for each call.

Redirects

To send the visitor elsewhere, use Tools::redirect() with a full URL. It sends a Location header and stops the script, so do it before any output:

PHP
<?php
// read-only
Tools::redirect($this->context->link->getPageLink('cart', true, null, ['action' => 'show']));

Prefer the link builder (getPageLink() for core pages, getModuleLink() for yours) over concatenated paths. Never redirect to a URL taken straight from the request; if you must support a "return to" address, accept only local paths (see Security in Modules).

Tokens

An action that changes data, such as "add to wishlist", can be triggered by another website that tricks a logged-in customer's browser into sending the request. This is CSRF, covered in Shop Security. The defense is a token tied to the customer's session that the attacker cannot guess.

On the storefront, PrestaShop provides a static token: templates receive it as $static_token, and PHP can compute it with Tools::getToken(false). Add it to forms and AJAX calls, and compare it in the controller before doing anything:

SMARTY
{* read-only template *}
<button data-url="{$link->getModuleLink('acmewishlist', 'toggle', ['id_product' => $product.id_product])}"
        data-token="{$static_token}">Save</button>

If the token is missing or wrong, answer with HTTP 403 and do nothing. Also remember that tokens are not authentication: use $auth = true (or check $this->context->customer->isLogged()) when the action belongs to a customer. Tokens belong to the page's session, so pages that are cached publicly must not embed one; load it with a small request or avoid caching those pages.

Stand-in: a controller lifecycle

The second stand-in implements a base controller with the stages above: access check, token check, postProcess, AJAX or page output, and a redirect for guests. It uses a simple HMAC as the token. A Request array stands for the PHP superglobals. The wishlist logic is a plain array.

PHP Stand-in: controller with auth, token, JSON and redirect

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.

Compare the run with the real code above: the guest is redirected before any logic runs ($auth), the token is checked before the action, numbers are cast to integers, and every answer has a status code that matches the result (403, 422, 200). What the stand-in does not show is the Smarty rendering and the theme layout; those are real-only.

Common mistakes

  • Wrong class name or folder. If the class is not ModuleNameControllerNameModuleFrontController in controllers/front/<controller>.php, the page is a 404.
  • No token check on actions that change data.
  • Echoing instead of using ajaxRender() or a template.
  • Forgetting to clear the cache after adding a route.
  • Trusting Tools::getValue() input without casting or validating.
  • Putting heavy logic into the controller. Keep controllers thin and move rules into classes you can test (Testing Modules).

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A module named acmewishlist has controllers/front/toggle.php. What should the class be called?

    The class name is the capitalized module name, then the capitalized controller name, then ModuleFrontController. Otherwise PrestaShop cannot find it.
  2. 2. How should a module link to its controller from PHP?

    getModuleLink() returns the correct form for the shop's URL settings, including friendly URLs and language prefixes.
  3. 3. Which hook lets a module register friendly URL rules for its controllers?

    The module registers the moduleRoutes hook and returns an array of routes with a rule, keywords and params.
  4. 4. An AJAX action changes the customer's wishlist. What protects it from cross-site request forgery?

    A token tied to the session cannot be guessed by another site. Without it, any page can trigger the request in a logged-in customer's browser.
  5. 5. What does public $auth = true do in a front controller?

    With $auth set, a guest never reaches your logic; PrestaShop sends them to the authentication page first.

Summary

  • A front controller lives in controllers/front/<name>.php and extends ModuleFrontController; the class is <Module><Name>ModuleFrontController.
  • Reach it with getModuleLink(); add pretty URLs with the moduleRoutes hook (rule, keywords with regular expressions, fc and module params).
  • The lifecycle is roughly init, postProcess, then displayAjax or initContent plus display.
  • Use $auth for customer-only pages, ajaxRender() with a status code and content type for JSON, and Tools::redirect() with generated URLs for redirects.
  • Protect actions with the static token ($static_token or Tools::getToken(false)) and validate all input.

Next, see how the HTML of these pages is produced and customized: Smarty Templates and Theme Integration.