Skip to content
Tutorials Center
My learning

Topics

Lesson 30 of 30 ยท Practice and Review

PrestaShop Module Cheat Sheet

A quick PrestaShop module reference: skeleton, naming rules, common hooks, Configuration/Db/Tools calls, console commands, routing YAML and an upgrade checklist.

This page is a lookup table, not a lesson. When you cannot remember how a front controller class is named, which Configuration call deletes a key or what a route file looks like, come here. Each section links back to the lesson that explains the idea. Targets are PrestaShop 8 and 9; class names, flags and defaults can differ slightly between versions, so check php bin/console list and the source of your installation when you need certainty.

PrestaShop cannot run on this site, so every real command, YAML and PHP snippet is read-only. Two small runnable plain-PHP stand-ins at the end generate the names PrestaShop expects and check a module manifest against the rules on this page. They are not PrestaShop code.

flowchart LR
    A["Need a name"] --> N["Naming table"]
    B["Need a call"] --> API["Configuration, Db, Tools"]
    C["Need a hook"] --> H["Hook list"]
    D["Need a command"] --> CLI["Console"]
    E["Shipping a release"] --> U["Upgrade checklist"]

Jump to the part that matches what you are looking for.

Module skeleton

TEXT
modules/acmething/
  acmething.php             main class AcmeThing extends Module
  config.xml                generated by PrestaShop
  logo.png                  32x32
  index.php                 empty "forbidden" stub (also in subfolders)
  composer.json             autoload, if you use namespaces
  controllers/front/*.php   front controllers
  controllers/admin/*.php   legacy admin controllers
  config/routes.yml         Symfony routes
  config/services.yml       Symfony services
  src/                      namespaced classes
  views/templates/hook/     hook templates
  views/templates/front/    front controller templates
  views/js/ views/css/      assets
  upgrade/upgrade-X.Y.Z.php upgrade scripts
  translations/             catalogs
PHP
<?php
if (!defined('_PS_VERSION_')) {
    exit;
}

class AcmeThing extends Module
{
    public function __construct()
    {
        $this->name = 'acmething';              // = folder name, lowercase
        $this->tab = 'front_office_features';
        $this->version = '1.0.0';
        $this->author = 'Acme';
        $this->need_instance = 0;
        $this->bootstrap = true;
        $this->ps_versions_compliance = ['min' => '8.0.0', 'max' => _PS_VERSION_];
        parent::__construct();

        $this->displayName = $this->trans('Acme Thing', [], 'Modules.Acmething.Admin');
        $this->description = $this->trans('What it does.', [], 'Modules.Acmething.Admin');
    }

    public function install(): bool
    {
        return parent::install()
            && $this->registerHook('displayHeader');
    }

    public function uninstall(): bool
    {
        return parent::uninstall()
            && Configuration::deleteByName('ACMETHING_LABEL');
    }
}

More in Anatomy of a Module and Your First Module.

Naming rules

Thing Rule Example
Module folder and $this->name lowercase letters and digits acmething
Main file <name>.php acmething.php
Main class the module name, PascalCase by convention AcmeThing
Front controller file controllers/front/<controller>.php controllers/front/toggle.php
Front controller class <Module><Controller>ModuleFrontController AcmethingToggleModuleFrontController
Admin controller class <Name>Controller (legacy) in controllers/admin/ AdminAcmeThingController
Hook method hook + hook name hookDisplayHeader
Upgrade file upgrade/upgrade-<version>.php upgrade-1.2.0.php
Upgrade function upgrade_module_<version with underscores> upgrade_module_1_2_0($module)
Configuration keys uppercase with your prefix ACMETHING_LABEL
Table names _DB_PREFIX_ + module prefix ps_acmething_item
Symfony route name vendor prefix, lowercase acme_thing_export
Translation domain Modules.<Name>.Admin or .Shop Modules.Acmething.Shop

Class names in PHP are case-insensitive, but follow the convention so the code reads like the rest of the ecosystem.

Common hooks

Hook Kind Typical use
displayHeader display Add tags or inline code in <head>
actionFrontControllerSetMedia action Register CSS and JavaScript for front pages
displayProductAdditionalInfo display Add content to the product page
displayShoppingCart display Add content to the cart page
displayFooter display Add content to the footer
displayHome display Add content to the home page
paymentOptions payment Return PaymentOption objects at checkout
paymentReturn payment Content on the order confirmation page
displayOrderConfirmation display Extra content after an order
actionValidateOrder action React to a new order
actionOrderStatusPostUpdate action React after an order state changed
actionCartSave action React when a cart is saved
actionCustomerAccountAdd action React to a new account
actionObjectProductUpdateAfter action React after a product was updated
displayBackOfficeHeader display Add tags to all back office pages
actionAdminControllerSetMedia action Register assets for legacy admin pages
action<Grid>GridDefinitionModifier action Change columns, filters, bulk actions of a grid
action<Grid>GridQueryBuilderModifier action Change the query of a grid

Use the hook list in the back office (Design > Positions) and the source of your version for exact names and parameters. See Common Front Office Hooks.

PHP
$this->registerHook(['displayHeader', 'actionValidateOrder']);   // in install()
$this->unregisterHook('displayHeader');                           // in uninstall or upgrade

public function hookDisplayHeader(array $params): string { /* ... */ }
public function hookActionValidateOrder(array $params): void { /* $params['order'] ... */ }

Hook::exec('actionAcmeThingDone', ['id' => $id]);                 // your own hook

Configuration, Db, Tools and friends

Task Call
Read a setting Configuration::get('ACMETHING_LABEL')
Read several Configuration::getMultiple(['A', 'B'])
Save a setting Configuration::updateValue('ACMETHING_LABEL', $value)
Delete a setting Configuration::deleteByName('ACMETHING_LABEL')
Check a key exists Configuration::hasKey('ACMETHING_LABEL')
Select rows Db::getInstance()->executeS($sql)
One row Db::getInstance()->getRow($sql)
One value Db::getInstance()->getValue($sql)
Run DDL or any statement Db::getInstance()->execute($sql)
Insert Db::getInstance()->insert('table', ['col' => $v]) (adds the prefix)
Update Db::getInstance()->update('table', ['col' => $v], 'id = ' . (int) $id)
Delete Db::getInstance()->delete('table', 'id = ' . (int) $id)
Last database error Db::getInstance()->getMsgError()
Escape a string for SQL pSQL($text) (bqSQL() for identifiers)
Read request input Tools::getValue('name', 'default'), Tools::getIsset('name')
Front CSRF token Tools::getToken(false)
Redirect Tools::redirect($url)
Validate Validate::isEmail($v), Validate::isLoadedObject($obj), Validate::isUnsignedInt($v)
Module URL $this->context->link->getModuleLink('acmething', 'toggle', [], true)
Page URL $this->context->link->getPageLink('cart')
Translate $this->trans('Text', [], 'Modules.Acmething.Shop')
JS variables for the theme Media::addJsDef(['acme' => ['url' => $url]])
Register front assets $this->context->controller->registerJavascript($id, $path, $options) and registerStylesheet(...)
Show a template $this->context->smarty->assign([...]); return $this->display(__FILE__, 'views/templates/hook/x.tpl');

Always prefix table names with _DB_PREFIX_ in raw SQL, cast numbers to integers and escape strings; see Security in Modules.

Smarty snippets

SMARTY
{$title|escape:'html':'UTF-8'}              {* escaped output *}
{$id_product|intval}                        {* number *}
{l s='Add to cart' d='Modules.Acmething.Shop'}   {* translated text *}
{hook h='displayAcmeThing' mod='acmething'} {* run a hook inside a template *}
{if $logged}...{else}...{/if}
{foreach from=$items item=item}...{/foreach}
{$html nofilter}                            {* raw output, only for markup you built *}

More in Smarty Templates and Theme Integration.

Console commands

Run from the shop root. Check php bin/console list for your version.

Task Command
List commands php bin/console list
Install a module php bin/console prestashop:module install acmething
Uninstall php bin/console prestashop:module uninstall acmething
Enable or disable php bin/console prestashop:module enable acmething / disable acmething
Reset (uninstall + install) php bin/console prestashop:module reset acmething
Run upgrade scripts php bin/console prestashop:module upgrade acmething
Configure a module php bin/console prestashop:module configure acmething
Clear the cache php bin/console cache:clear (add --env=prod for production)
Show routes php bin/console debug:router
Show a service php bin/console debug:container <service id>
Optimise Composer autoload in a module composer dump-autoload -o
Syntax check a file php -l modules/acmething/acmething.php

Development mode (error display and no cache reuse) is controlled by a constant in the shop configuration; in many versions _PS_MODE_DEV_ in config/defines.inc.php. Switch it off in production. See Setting Up a Development Environment.

Routing and services

config/routes.yml:

YAML
acme_thing_export:
  path: /acme/things/export
  methods: [POST]
  defaults:
    _controller: 'PrestaShop\Module\AcmeThing\Controller\Admin\ExportController::exportAction'
    _legacy_controller: AdminOrders

config/services.yml:

YAML
services:
  _defaults:
    autowire: true
    public: true

  PrestaShop\Module\AcmeThing\:
    resource: '../src/*'

composer.json autoload:

JSON
{
  "name": "acme/acmething",
  "type": "prestashop-module",
  "autoload": { "psr-4": { "PrestaShop\\Module\\AcmeThing\\": "src/" } }
}

Security on a Symfony action is declared with the admin security annotation (@AdminSecurity) or, in newer versions, the PHP attribute. See The Symfony Back Office and Twig, Forms and Grids.

Upgrade files

PHP
<?php
// upgrade/upgrade-1.2.0.php
if (!defined('_PS_VERSION_')) {
    exit;
}

function upgrade_module_1_2_0($module): bool
{
    return (bool) Db::getInstance()->execute(
        'ALTER TABLE `' . _DB_PREFIX_ . 'acmething_item` ADD COLUMN `note` VARCHAR(255) NULL'
    );
}

Write scripts so they can run twice without harm (check whether the column exists first), and return true only on success. See Tables, Installers and Upgrades.

Release and upgrade checklist

  1. Bump $this->version and add upgrade/upgrade-<version>.php when data or hooks change.
  2. Test a fresh install and an upgrade from the previous version on a copy of a real shop.
  3. Test uninstall and a second install: tables, configuration keys, hooks and tabs must be gone, then back.
  4. Check every new request path: login required? token? input validated? output escaped?
  5. Check multistore: are settings per shop where they should be?
  6. Check translations: all visible text goes through trans().
  7. Run the PHP syntax check and any static analysis or the PrestaShop validator your marketplace requires; see Testing Modules.
  8. Keep ps_versions_compliance honest: test on the minimum version you claim.
  9. Remove debug output, test keys and development files before zipping the module.
  10. Zip the module so the folder name equals the module name inside the archive.

Two stand-ins

The first stand-in turns a module name, controller, hook and version into the names from the naming table. It is handy for checking your own files against the conventions.

PHP Generate the names PrestaShop expects

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 second stand-in is a tiny linter. It receives a description of a module (a manifest) and reports the problems the checklist above would catch. It cannot inspect real files; it shows how mechanical most review rules are.

PHP Check a module manifest against the rules

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 ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is the class name pattern for a module front controller?

    For module acmething and controller toggle, the class is AcmethingToggleModuleFrontController (case does not matter to PHP).
  2. 2. Which function name does PrestaShop look for in upgrade/upgrade-1.2.0.php?

    The version dots become underscores, and the function receives the module instance and returns a boolean.
  3. 3. Why does the release checklist include testing a second install after uninstall?

    Leftover tables or settings from a bad uninstall are a common cause of failed reinstalls.
  4. 4. Which statement about Configuration keys is the best practice?

    A prefix avoids clashes with other modules, and deleting them on uninstall leaves the shop clean.

Summary

  • The module folder, $this->name and the main file share one lowercase name; controllers, hooks, upgrades and keys follow fixed patterns.
  • Configuration, Db, Tools, Validate, Media and Link cover most everyday module calls; always escape and cast.
  • Module management and cache clearing run through php bin/console.
  • Symfony pages need config/routes.yml, config/services.yml and a permission declaration.
  • Ship with an upgrade file, a tested fresh install, upgrade and uninstall, and honest version compatibility.

You have reached the end of the track. Revisit any topic from What PrestaShop Is and How It Is Built, or repeat the Practice Exercises with Solutions without looking at the answers.