Skip to content
Tutorials Center
My learning

Topics

Lesson 8 of 30 ยท Hooks

Creating and Dispatching Your Own Hooks

Add your own extension points to a PrestaShop module with Hook::exec: naming, registering hooks in the database, aliases, collecting results and versioning parameters.

Until now you have listened to hooks that PrestaShop core and other modules fire. The same mechanism is open to you: any module can call Hook::exec() at a moment of its own choosing, and other modules can react without touching your code. A loyalty module can announce "points were earned", a shipping module can ask "who wants to add a delivery option?", and a theme can ask for extra HTML in a spot you define.

Adding a hook is cheap. Keeping it stable is the real work, because once another module depends on its name and parameters, it is part of your public interface. This lesson shows how to fire a hook, how hooks live in the database, what aliases are, how to collect results from several listeners, how Symfony code dispatches hooks, and how to evolve parameters without breaking anyone. It follows Common Front Office Hooks.

Firing a hook with Hook::exec

Hook::exec() is the function behind every hook call in the core. A simplified view of its signature (check your version for the full list):

PHP
<?php
// read-only: PrestaShop 8 style
Hook::exec(
    string $hook_name,
    array $hook_args = [],
    ?int $id_module = null,
    bool $array_return = false,
    bool $check_exceptions = true
);
  • $hook_name is the hook, for example actionAcmeLoyaltyPointsAdded.
  • $hook_args is the array every listener receives as $params.
  • $id_module limits the call to one module. Leave it null to call everyone registered.
  • $array_return: when false (the default) the results of all listeners are joined into one string, which is what display hooks need. When true you get an array that maps each module name to what it returned, which is what you want when you need to inspect or combine results.
  • $check_exceptions: when true, an exception thrown inside a listener is caught and logged so one broken module does not take down the page.

A typical use in your own module:

PHP
<?php
// read-only
class AcmeLoyalty extends Module
{
    public function addPoints(Customer $customer, int $points): void
    {
        // ... save the points ...

        Hook::exec('actionAcmeLoyaltyPointsAdded', [
            'id_customer' => (int) $customer->id,
            'points' => $points,
        ]);
    }

    public function renderPanel(Customer $customer): string
    {
        // Display hook: every listener returns HTML; the strings are joined.
        return Hook::exec('displayAcmeLoyaltyPanel', [
            'id_customer' => (int) $customer->id,
        ]);
    }

    /** @return array<string, mixed> module name => result */
    public function collectRewards(Customer $customer): array
    {
        return Hook::exec('actionAcmeLoyaltyCollectRewards', [
            'id_customer' => (int) $customer->id,
        ], null, true);
    }
}

Naming your hooks

Hook names share one namespace for the whole shop, so a bad name collides with someone else's.

  • Start with action for events and display for HTML, like the core does.
  • Put your module name right after the prefix: actionAcmeLoyaltyPointsAdded, displayAcmeLoyaltyPanel. A generic name such as actionPointsAdded may be fired by two different modules for two different meanings.
  • Use camelCase and describe the moment (Before, After) or the data.
  • Do not encode implementation details that may change.

Registering the hook in the database

Hooks are rows in the hook table (columns include id_hook, name, title, description, position and live_edit). Listeners are rows in hook_module, linking a hook, a module and a shop with a position.

You usually do not create the hook row yourself. When a module calls registerHook('actionAcmeLoyaltyPointsAdded') and no hook with that name exists, PrestaShop creates it for you. So the common flow is:

  1. Your module fires the hook with Hook::exec().
  2. Another module's install() calls registerHook() with that name, which creates the row (if needed) and the link.

If you want a proper title and description in the back office, create the hook yourself in your install():

PHP
<?php
// read-only
public function install(): bool
{
    if (!parent::install()) {
        return false;
    }

    if (!Hook::getIdByName('actionAcmeLoyaltyPointsAdded')) {
        $hook = new Hook();
        $hook->name = 'actionAcmeLoyaltyPointsAdded';
        $hook->title = 'Loyalty points added';
        $hook->description = 'Fired after points were saved for a customer.';
        $hook->position = false;
        $hook->live_edit = false;
        $hook->add();
    }

    return true;
}

Hook names are looked up case-insensitively, but write them in exact camelCase anyway so code, database and documentation agree.

When your module is uninstalled, remove only the hooks your module created, and only if no other module is still registered on them. Deleting a hook that others listen to leaves them with dead registrations.

Aliases

PrestaShop renamed many hooks over the years (for example the old header became displayHeader). To keep old modules working, the hook_alias table maps a retired name to the current one. When a module registers or fires a hook under an alias, PrestaShop resolves it to the canonical name, so the old module still receives the new hook.

For your own hooks an alias is a migration tool. If you rename actionAcmePointsAdded to actionAcmeLoyaltyPointsAdded, add an alias row for the old name and existing listener modules keep working while their authors update. Remove the alias after a few releases and say so in your changelog. Aliases are an advanced tool; for a young module, picking a good name the first time is better.

Collecting results

A hook that only announces an event needs no return value. But a hook can also be a question: "does anyone want to add a reward?" To ask, fire it with $array_return = true and read the array:

PHP
<?php
// read-only
$answers = Hook::exec('actionAcmeLoyaltyCollectRewards', ['id_customer' => 12], null, true);
// ['acmegift' => ['label' => 'Free gift', 'points' => 100], 'acmeship' => ['label' => 'Free shipping', 'points' => 50]]

Each key is a module name, so you can see who answered what. Always validate the answers: listeners are third-party code, so one may return null, a string, or a malformed array. Check types and skip bad entries rather than trusting them.

Hooks are not filters. The core has no built-in "pass the value through every listener and return the final value" like some other platforms. If you want a value to be modified, either pass an object that listeners can change, or pass a variable by reference inside the array:

PHP
<?php
// read-only
$label = 'Standard delivery';
Hook::exec('actionAcmeShippingLabel', ['label' => &$label]);
// A listener can now write $params['label'] = 'Standard delivery (green)';

Be careful with this pattern: the order of listeners then matters, and two modules may overwrite each other. Document it clearly.

sequenceDiagram
    participant M as "Your module"
    participant H as "Hook::exec"
    participant L1 as "acmegift"
    participant L2 as "acmeship"
    M->>H: "actionAcmeLoyaltyCollectRewards, array_return true"
    H->>L1: "hookActionAcmeLoyaltyCollectRewards(params)"
    L1-->>H: "reward array"
    H->>L2: "hookActionAcmeLoyaltyCollectRewards(params)"
    L2-->>H: "reward array"
    H-->>M: "array: module name => result"

Every registered listener is called in position order; the answers come back keyed by module name.

Stand-in: a dispatcher that collects results

This stand-in is not PrestaShop code. It mimics three real ideas: a hook table with aliases, exec() with the string result or an array keyed by module name, and exception isolation. Run it and check each line of output against the explanation above.

PHP Stand-in: hook table, aliases and results

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.

Three things to notice. The broken module's failure is logged and the other answers still arrive. The display hook joins two strings in registration order. And the second display listener was registered under an upper-case name but still reached the same hook, like the case-insensitive lookup in the real database.

Hooks from Symfony code

Back office pages built with Symfony controllers (see The Symfony Back Office) fire hooks too, but through a service rather than the static Hook::exec(). PrestaShop provides a hook dispatcher service, prestashop.hook.dispatcher, which also turns hook calls into Symfony events so that both module styles can listen. In a controller or service you will see calls like these:

PHP
<?php
// read-only: names as in PrestaShop 8, verify against your version
$dispatcher = $this->get('prestashop.hook.dispatcher');

// An action hook (nothing to render):
$dispatcher->dispatchWithParameters('actionAcmeOrderExported', ['id_order' => $orderId]);

// A display hook (collects the rendered output of all listeners):
$html = $dispatcher->dispatchRenderingWithParameters('displayAcmeExportPanel', ['id_order' => $orderId]);

Admin controllers that extend PrestaShop's base admin controller also have a small dispatchHook() helper. The rule for your own modules is simple: use Hook::exec() in legacy classes and controllers, and the dispatcher service in Symfony services. Listeners written with a classic hookActionXxx method receive both.

Versioning hook parameters

A hook's name plus its parameters is a contract. To change it without breaking listeners:

  • Adding a key is safe. Old listeners ignore it.
  • Renaming, removing or retyping a key is breaking. Add the new key, keep the old one for a few releases, and document the deprecation.
  • Never change the meaning of an existing key (for instance from tax-excluded to tax-included cents).
  • Pass identifiers and plain values in addition to objects, so a listener can avoid loading a whole entity.
  • Consider a version key such as 'api_version' => 2 when you expect big changes; listeners can branch on it.
  • Write defensively as a listener: read with $params['key'] ?? default and check types.

The second stand-in plays through a parameter change. Version 1 of our hook passed an integer amount; version 2 adds amount_cents, currency and api_version but keeps amount as a deprecated duplicate. An old listener keeps working and a new one uses the better data.

PHP Stand-in: evolving hook parameters

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 block prints Warning: Undefined array key "amount" on purpose. That is PHP telling you the old listener broke, and it is what a shop owner would find in the logs after a careless release. The Warning line is expected; the other lines are the normal output.

Document and test

Write the hook's name, when it fires, every parameter with its type and unit, and the first version in which it appeared, in your module's README. Test it: fire the hook in a test with a stub listener and assert that the parameters match your documentation (Testing Modules).

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does Hook::exec() return by default when listeners return HTML strings?

    By default the results are concatenated into one string, which is what display hooks need. Pass $array_return = true to get an array keyed by module name instead.
  2. 2. Which hook name is the best choice for an event in a module called acmeloyalty?

    Hook names share one namespace. Starting with action and including the module name makes collisions unlikely and the purpose clear.
  3. 3. A module registers on a hook that does not exist yet. What happens?

    registerHook() creates the hook in the database when it is missing, which is why modules can listen to hooks fired by other modules.
  4. 4. Which change to a hook's parameters is safe for existing listeners?

    Listeners ignore keys they do not know. Renaming, changing the meaning or removing keys breaks code that reads them.
  5. 5. What is the job of the hook_alias table?

    Aliases keep modules written for retired hook names working by resolving the old name to the current one.

Summary

  • Hook::exec($name, $args, $id_module, $array_return) fires a hook; the default result is a joined string, and $array_return = true gives an array keyed by module name.
  • Name hooks action... or display... plus your module name, in camelCase.
  • Hooks are rows in hook; listeners are rows in hook_module. registerHook() creates a missing hook, and you can add a title and description yourself.
  • Aliases map old names to current ones and help you rename hooks gently.
  • Validate what listeners return; pass by-reference values only when you must and document the order effects.
  • Symfony code uses the prestashop.hook.dispatcher service instead of Hook::exec().
  • Treat parameters as a contract: add keys, never silently rename, remove or change them.

Next, see why hooks are usually a better choice than the heavier alternative: Overrides vs Hooks.