Skip to content
Tutorials Center
My learning

Topics

Lesson 3 of 30 ยท Module Basics

Anatomy of a Module

Learn the folder layout of a PrestaShop module, the main class, config.xml, logo, naming rules, install and uninstall, and composer autoloading with a mini loader.

A PrestaShop module is, at its simplest, a folder with a PHP file in it. But real modules grow: they have templates, translations, SQL, upgrade scripts, Symfony configuration and tests. If you know what each folder is for, you can open any module from any author and find your way in minutes.

This lesson walks through the layout of a module, the rules PrestaShop applies to names, the role of config.xml and the logo, the install() and uninstall() methods, and Composer autoloading. The real code is read-only; the stand-ins are a mini module loader that applies the same naming and lifecycle rules, and a package checker.

The folder layout

Modules live in the modules/ directory of the shop. A medium-sized module looks like this:

TEXT
modules/hellomodule/
  hellomodule.php          main class, same name as the folder
  config.xml               module metadata (generated by PrestaShop)
  logo.png                 icon shown in the module list
  index.php                empty "do nothing" file (also in every subfolder)
  composer.json            autoloading and dependencies
  vendor/                  Composer packages (shipped with the module)
  src/                     your own classes (namespaced)
  controllers/
    front/                 front controllers
    admin/                 legacy admin controllers
  views/
    templates/
      front/               templates for front controllers
      hook/                templates rendered by hooks
      admin/               templates for the back office
    css/  js/  img/        assets
  sql/                     SQL used by the installer
  upgrade/                 upgrade-1.1.0.php, upgrade-1.2.0.php ...
  translations/            translation catalogs
  config/                  routes.yml, services.yml (Symfony part)

You do not need all of it. Only the folder, the main PHP file and a few properties are required. Everything else is added when you need it. Notice the convention: PHP classes in src/, templates in views/templates/, and assets in views/css, views/js and views/img. Sticking to the standard names matters, because PrestaShop and its tools look in exactly these places.

The empty index.php in every folder is a leftover of the days when web servers listed folder contents by default. It prints nothing (or redirects), so a visitor who types the folder URL does not see a file listing. The official validator expects these files, and the module generators create them for you.

The main class

The main file has the same name as the folder (hellomodule.php), and contains one class that extends Module:

PHP
<?php
// modules/hellomodule/hellomodule.php
if (!defined('_PS_VERSION_')) {
    exit;
}

class Hellomodule extends Module
{
    public function __construct()
    {
        $this->name = 'hellomodule';
        $this->tab = 'front_office_features';
        $this->version = '1.0.0';
        $this->author = 'Your Name';
        $this->need_instance = 0;
        $this->ps_versions_compliancy = ['min' => '8.0.0', 'max' => _PS_VERSION_];

        parent::__construct();

        $this->displayName = $this->trans('Hello module', [], 'Modules.Hellomodule.Admin');
        $this->description = $this->trans('A first example module.', [], 'Modules.Hellomodule.Admin');
    }

    public function install()
    {
        return parent::install();
    }

    public function uninstall()
    {
        return parent::uninstall();
    }
}

Three details are worth understanding now:

  1. The _PS_VERSION_ guard. A module file can in principle be requested directly through the web server. The first line stops execution unless the file was loaded by PrestaShop (which defines this constant). Every PHP file in a module that is not a pure class definition should start with it.
  2. The name rule. $this->name must equal the folder name, and the class name must match it apart from capitalization (the usual convention is the folder name with a capital first letter, such as Hellomodule). Use lowercase letters, digits and underscores; avoid spaces, dashes and dots. Because the name becomes a key in the database, treat it as permanent: renaming it later is like creating a different module.
  3. The parent::__construct() call. It must come after you set name and the other properties, because the parent class uses them (it reads or creates config.xml, for instance). The translated displayName can only be set after it, since translations need the name.

config.xml holds a copy of the module's metadata: name, display name, version, author, tab (category), whether it needs an instance, and whether it can be configured. PrestaShop generates it automatically the first time the module is loaded in the back office. You normally do not write it by hand. It is used to show the module list quickly, without instantiating each class. A stale config.xml (shipped from an old version) can show outdated information, so remove it from the package or let PrestaShop regenerate it after a version change.

logo.png is the small icon in the module manager (a 32 by 32 pixel PNG is the usual size). It is optional, but a module without a logo looks unfinished in the back office.

install() and uninstall()

When an administrator clicks Install, PrestaShop includes the main file, creates your class and calls install(). Your job is to prepare everything the module needs and to return true only if all of it worked. A typical install() does four things:

PHP
public function install()
{
    return parent::install()                 // registers the module in the database
        && $this->registerHook('displayHeader')  // attach to hooks
        && Configuration::updateValue('HELLOMODULE_GREETING', 'Hello!')   // default settings
        && $this->installSql();               // custom tables (see the data lessons)
}

public function uninstall()
{
    return parent::uninstall()
        && Configuration::deleteByName('HELLOMODULE_GREETING')
        && $this->uninstallSql();
}

The && chain stops at the first step that returns false, and a false result makes PrestaShop show an error and leave the module not installed. Be careful, though: steps that ran before the failure are not undone. If registerHook succeeded and a table creation failed, the hook registration stays. Good modules make their install steps idempotent (safe to run twice) and clean up after themselves in uninstall().

Uninstall must remove what install created: configuration keys, custom tables, and any tabs or hooks you added. A module that leaves data behind is one of the most common review complaints. The rule is: everything install() adds, uninstall() removes (apart from data that merchants may want to keep, which you can offer as an option).

flowchart TD
    A["Admin clicks Install"] --> B["Include main file<br/>and create the class"]
    B --> C["install()"]
    C --> D{"All steps returned true?"}
    D -->|"yes"| E["Module recorded as installed<br/>hooks registered"]
    D -->|"no"| F["Error shown<br/>module not installed"]
    E --> G["Admin clicks Uninstall"]
    G --> H["uninstall()<br/>remove settings, tables, hooks"]

Install runs your code once; uninstall must undo the changes that install made.

Composer and autoloading

Plain module code uses require_once or PrestaShop's old class loading. Modern modules instead use Composer with a PSR-4 autoloader, so that every class in src/ is loaded automatically:

JSON
{
  "name": "acme/hellomodule",
  "description": "A first example module",
  "type": "prestashop-module",
  "license": "AFL-3.0",
  "autoload": {
    "psr-4": {
      "Acme\\Hellomodule\\": "src/"
    }
  },
  "config": {
    "prepend-autoloader": false
  }
}

With this file, a class Acme\Hellomodule\Service\Greeter lives in src/Service/Greeter.php. You run composer install --no-dev and ship the resulting vendor/ folder with the module, because the merchant's server will not run Composer for you. Load the autoloader once at the top of the main file:

PHP
if (file_exists(__DIR__ . '/vendor/autoload.php')) {
    require_once __DIR__ . '/vendor/autoload.php';
}

The prepend-autoloader: false setting keeps your module's autoloader from taking precedence over the shop's own, which prevents conflicts when two modules ship the same library in different versions. Namespace your own code carefully (vendor name first, as above), and be wary of bundling popular libraries unscoped: if two modules ship different versions of the same library under the same namespace, whichever loads first wins.

A mini module loader

The stand-in below does not touch PrestaShop. It models a small "filesystem" as an array and applies the rules above: the main file must match the folder name, the class must match the name, install() must return a boolean and uninstall must clean up. It is a teaching model of the lifecycle, not an emulation of the real Module class.

PHP A mini module loader with install and uninstall

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.

Checking a package before you ship it

A module is distributed as a ZIP file whose top-level folder is the module name. Before shipping, check that all expected files exist. The second stand-in checks a list of paths (a pretend ZIP listing) for common mistakes. The real PrestaShop Validator and your own review do much more, but these checks catch most beginner packaging errors.

PHP A package checker

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.

Common mistakes

  • Folder and class name differ. The module does not load, or loads under the wrong name. Match them exactly (apart from the first capital letter).
  • Forgetting return. install() must return a boolean. A missing return yields null, which counts as failure.
  • Not cleaning up. Settings and tables left behind pile up and clash with later installs.
  • Editing install() and expecting existing shops to change. Install code runs once. Changes for shops that already have your module belong in upgrade scripts, covered in Tables, Installers and Upgrades.
  • Shipping development files. Tests, Git folders and editor settings do not belong in the ZIP.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is the relationship between a module's folder name and its main class?

    PrestaShop finds the main file by the folder name and expects a class whose name matches. Keep $this->name equal to the folder name.
  2. 2. Why does install() return a boolean?

    The return value tells the module manager whether to record the module as installed. Use && to chain steps and return the result.
  3. 3. Which statement about config.xml is correct?

    config.xml caches module metadata. It is generated automatically, so shipping an old copy can cause stale displays.
  4. 4. What should uninstall() do?

    Uninstall mirrors install. Leaving data behind causes clutter and conflicts on reinstall.
  5. 5. Why is the PS_VERSION check at the top of module files?

    Direct requests do not define PS_VERSION, so the file exits instead of running outside the application.

Summary

  • A module is a folder under modules/ with a main file and class named like the folder, extending Module.
  • Standard places: src/ for classes, views/templates/ for templates, controllers/, upgrade/, sql/, translations/, config/.
  • config.xml is generated metadata; logo.png is the icon; every folder gets an index.php.
  • install() prepares the module and returns a boolean; uninstall() undoes everything install created.
  • Use Composer PSR-4 autoloading and ship vendor/ with the module.

Next: Your First Module