Skip to content
Tutorials Center
My learning

Topics

Lesson 22 of 30 ยท Quality and Security

Performance and Caching

Keep PrestaShop modules fast: Smarty template caching with cache ids, in-request caching, avoiding N+1 queries in hooks, loading assets only where needed and profiling, with runnable query counters.

A module is not fast or slow on its own: it adds its cost to every page where its hooks run. A hook on the product page that runs one extra query is invisible. A hook in the header that runs thirty queries on every page of a shop with a million visits a month is a real problem. Shop owners rarely know which module is responsible, they just see a slow store and blame the platform.

This lesson shows where a module typically wastes time and what PrestaShop gives you to fix it: Smarty template caching, request-level caching with Cache::store(), batch queries instead of one query per item, loading CSS and JavaScript only on the pages that need them, and measuring before you optimize. Real code is read-only; the runnable examples are stand-ins that count queries and cache hits so the effect is visible. For the matching theory about scaling a whole shop see Architecture and Scaling.

Measure first

Do not guess. Switch the shop to development mode (see Setting Up a Development Environment) and look at what a page really does. The Symfony profiler toolbar in the back office shows time, memory and the database queries of a page. For the front office, PrestaShop has a profiling switch (the _PS_DEBUG_PROFILING_ constant in the configuration defines) that prints timing and query information at the bottom of the page, including which queries are slowest and how often they repeat. Repeated identical queries are the most useful clue.

Always profile in development mode but judge speed in production mode, because development mode disables caches and adds overhead. A page that is 300 ms in production might be 3 seconds in debug mode.

flowchart LR
    A["Measure<br/>(profiler, query log)"] --> B["Find the hot spot"]
    B --> C["Fix: batch, cache or skip"]
    C --> D["Measure again"]
    D --> B

Optimize in a loop: one change, one measurement.

Avoid N+1 queries in hooks

The N+1 problem is the most common performance bug in modules. You load a list of N items with one query, then loop over it and run one more query per item, giving N+1 queries. A product list with 24 items turns into 25 queries; a category page with several such widgets multiplies the cost.

The fix is to ask the database for everything at once with an IN (...) list or a join, and then index the result by id in PHP. In PrestaShop, remember that integer lists must be cast:

PHP
$ids = array_map('intval', array_column($products, 'id_product'));

$rows = Db::getInstance()->executeS(
    'SELECT id_product, badge
     FROM `' . _DB_PREFIX_ . 'mymodule_badge`
     WHERE id_product IN (' . implode(',', $ids) . ')'
);

$badges = [];
foreach ($rows as $row) {
    $badges[(int) $row['id_product']] = $row['badge'];
}

Guard against an empty list first, because IN () is a syntax error. The same advice applies when you use ObjectModel: creating new Product($id) inside a loop runs queries for every item. Where possible read the columns you need with one query. Core helpers also take lists, such as Product::getProductsProperties() for many products at once, so look for a plural method before writing a loop.

The first stand-in compares the two approaches with a query counter.

PHP Counting queries: N+1 versus one batch

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.

Cache inside one request

Hooks run several times per page and different modules may ask for the same thing: the shipping rules, a configuration list, a computed result for the same product. PrestaShop has a tiny static cache for this, Cache::store($key, $value), Cache::isStored($key) and Cache::retrieve($key). It lives only for the current request, so it never serves stale data to another visitor, which makes it the safest first optimization.

PHP
$key = 'mymodule_rules_' . (int) $idShop;

if (!Cache::isStored($key)) {
    Cache::store($key, $this->loadRulesFromDatabase((int) $idShop));
}

$rules = Cache::retrieve($key);

Make the key contain everything that changes the answer: the shop, the language, the currency, the customer group. A key that is too short returns the wrong data.

The Configuration class already loads all configuration values in one go and keeps them in memory, so calling Configuration::get() in a loop is cheap. Likewise Context::getContext() returns the shared context object that already holds the shop, language, currency, cart and customer. Use it instead of querying for them again.

Cache rendered templates with Smarty

Rendering a template and the queries that fill it can be cached together. A Smarty cache entry is identified by the template and a cache id. If the output depends on the language, the shop or the currency, the cache id must include them, otherwise a French visitor will see the English version.

PHP
public function hookDisplayFooter($params)
{
    $template = 'module:mymodule/views/templates/hook/footer.tpl';
    $cacheId = $this->getCacheId($this->name . '|' . (int) $this->context->language->id);

    if (!$this->isCached($template, $cacheId)) {
        $this->context->smarty->assign('links', $this->loadFooterLinks());
    }

    return $this->fetch($template, $cacheId);
}

If the cache is not yet filled, you assign the variables (which runs the queries); if it is, fetch() returns the stored HTML and the queries are skipped. getCacheId() already adds the shop and some context to the id you give it.

Caching creates one new job: invalidation. When the data changes, delete the stale entries. Do it from the hooks that fire on change, or in your admin save code:

PHP
public function hookActionObjectProductUpdateAfter($params)
{
    $this->_clearCache('*');
}

Do not cache anything that depends on the individual visitor, such as the cart contents, the customer name or prices that vary per customer group, unless the cache id includes that variable. Also remember that the shop owner must enable Smarty caching in Advanced Parameters, Performance. In development mode, the caches are usually off, so test caching behavior in production-like settings.

The second stand-in implements the same logic as isCached(), fetch() and _clearCache(): a render cache keyed by template and cache id, with counters.

PHP A Smarty-style render cache with cache ids

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 two lines show the classic mistake: the French visitor receives the English page, because the cache id did not distinguish them.

The database cache

PrestaShop also has an optional query cache for Db::getInstance()->executeS(), which can store results using a cache system such as Memcached or APCu when the shop owner turns it on. Individual calls can opt out: the signature is executeS($sql, $array = true, $use_cache = true). Pass false for queries that must always be fresh, such as stock checks in a payment step, and for queries that return large or personal results. Results of writes are not cached. If you rely on this cache, be aware that other modules and the core are using it too, so do not assume a particular backend exists.

Assets: load only where needed

CSS and JavaScript are often the largest cost a module adds. Register them in the actionFrontControllerSetMedia hook, which gives you a chance to look at the current page before adding files:

PHP
public function hookActionFrontControllerSetMedia()
{
    if ($this->context->controller->php_self !== 'product') {
        return;
    }

    $this->context->controller->registerStylesheet(
        'mymodule-product',
        'modules/' . $this->name . '/views/css/product.css',
        ['media' => 'all', 'priority' => 150]
    );
    $this->context->controller->registerJavascript(
        'mymodule-product',
        'modules/' . $this->name . '/views/js/product.js',
        ['position' => 'bottom', 'priority' => 150]
    );
}

Doing this once per page type, instead of in displayHeader for every page, saves two requests and some parsing on all other pages. A product-page script should not be in the cart page's source. The shop's Performance page can also combine, compress and cache CSS and JavaScript (CCC), and a module that registers its files through the proper API takes part in that automatically, while a hard-coded <script> tag in a template does not. Keep files small, avoid large libraries for tiny effects, and defer anything that is not needed for the first paint. The hooks used are described in Common Front Office Hooks.

Work that is slow but not urgent (sending data to an outside service, rebuilding an export) should not run while the customer waits. Run it from a cron job or a console command, or on a queue, and store the result in a table that the page reads quickly.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A hook loops over 30 products and runs one query for each. What is this problem called?

    One query for the list plus one per item gives N+1 queries. Fetch all related rows in one query and index them by id.
  2. 2. What is the safest first kind of cache for data that several hooks need on the same page?

    Cache::store() lives for the current request only, so it can never serve outdated data to a later visitor.
  3. 3. Your footer shows links in the visitor's language. What must the Smarty cache id contain?

    The cache id must identify every variation of the output. Without the language, one language's page is served to everyone.
  4. 4. Why register a stylesheet inside actionFrontControllerSetMedia and check the page?

    Registering through the API lets PrestaShop optimize the file, and a page check keeps unneeded files off other pages.
  5. 5. A module caches a rendered block that shows the customer's first name. What goes wrong?

    Per-visitor data must not be part of a shared cache unless the cache id includes it. Otherwise one visitor's data leaks to others.

Summary

  • Measure first with the profiler and the query log; judge speed in a production-like mode.
  • Fix N+1 problems by loading related rows in one IN (...) query and indexing them in PHP.
  • Use Cache::store() for request-level caching, and put every varying factor into the key.
  • Cache rendered hooks with isCached()/fetch() and a precise cache id, and clear the cache when the data changes.
  • Register CSS and JavaScript through the controller API, only for the pages that need them.
  • Move slow background work out of the page request.

Next: Testing Modules