Skip to content
Tutorials Center
My learning

Topics

Lesson 28 of 30 ยท Practice and Review

Practice Exercises with Solutions

Ten hands-on PrestaShop module exercises on hooks, configuration, ObjectModel, upgrades, controllers, templates and security, each with a runnable plain-PHP solution.

Reading about hooks and ObjectModel is one thing; writing the logic yourself is how it sticks. This lesson gives you ten exercises that mirror what you do in real modules: dispatch hooks in the right order, validate a settings form, define an entity, run upgrades, answer ajax calls, protect against forged requests, escape output, avoid SQL injection and translate text.

PrestaShop cannot run on this site, so the exercises use plain-PHP stand-ins. They are not PrestaShop code, but the rules they practise are the same ones the real classes follow. Each group of exercises ends with a runnable solution. Try to write your own version first, in a scratch file or in the editor, before you open the solution.

flowchart TD
    E["Ten exercises"] --> H["Hooks<br/>1 and 2"]
    E --> D["Data and config<br/>3, 4 and 5"]
    E --> C["Controllers<br/>6 and 7"]
    E --> S["Output and safety<br/>8, 9 and 10"]

Four groups, each ending in a complete solution you can run and change.

Group 1: hooks

Hooks are the heart of module work; see Hooks: How Modules Plug In and Creating and Dispatching Your Own Hooks.

Exercise 1: a display hook dispatcher. Write a HookDispatcher with register($hook, $module, $callable, $position) and display($hook, $params). Modules registered on the same hook run in ascending position order (ties by registration order), and the output of every module is concatenated. A module that is disabled must be skipped.

Exercise 2: an action hook that changes data. Action hooks do not return HTML; they receive parameters by reference so listeners can change them. Add an action($hook, array &$params) method, then register two listeners on actionPriceModify: one gives 10% off, one adds a flat shipping fee of 5. Show that the order of positions changes the final result.

PHP Solutions 1 and 2: hook dispatcher

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.

Discount first gives 100 * 0.9 + 5 = 95; the fee first gives (100 + 5) * 0.9 = 94.5. In a real shop you move modules between positions in the back office, so action hooks that modify shared values should be written to tolerate any order, or document the order they need.

Group 2: configuration, entities and upgrades

See A Module Configuration Page, ObjectModel and Entities and Tables, Installers and Upgrades.

Exercise 3: validate a settings form. A module has three settings: label (1 to 30 characters), threshold (an integer from 0 to 1000) and api_url (an https URL). Write validateSettings(array $input) returning the cleaned values and a list of errors. Save to the configuration store only when there are no errors; otherwise keep the old values.

Exercise 4: a mini ObjectModel. Write a base class whose children declare a $definition array (table, primary key, fields with a type, a required flag and a size). Implement validate() and add() on SQLite, so an invalid object throws and nothing is stored.

Exercise 5: an upgrade runner. The installed version is 1.0.0, the new code is 1.10.0, and upgrade scripts exist for 1.1.0, 1.2.0 and 1.10.0. Run only the scripts newer than the installed version, in version order. Show why sorting version strings with plain string comparison goes wrong.

PHP Solutions 3, 4 and 5: settings, entity, upgrades

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 most useful part of exercise 5 is the string sort: 1.10.0 lands before 1.2.0 as text, so a runner that sorted file names alphabetically would run the scripts in the wrong order. version_compare understands version numbers.

Group 3: controllers and tokens

See Module Front Controllers and Security in Modules.

Exercise 6: a controller router. Write a FrontRouter that maps a controller name to a function and answers [status, json]. Unknown controllers return 404, and a method the controller does not allow returns 405.

Exercise 7: a CSRF token. Create a token from a secret and the session id, and reject any POST whose token does not match, comparing in constant time. Show that a token from another session fails.

PHP Solutions 6 and 7: router and token

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 router answers 404 and 405 correctly and the handler refuses missing and foreign tokens (as a bonus exercise, make it return a 403 status instead of 200 with ok: false). Notice that the third request is a GET to a POST-only controller: a clear 405 is friendlier to debug than a silent success.

Group 4: output and safety

See Smarty Templates and Theme Integration, Security in Modules and Translations and Multilingual Modules.

Exercise 8: a template that escapes by default. Write a tiny render($template, $vars) that replaces {$name} with the HTML-escaped value, and {$name nofilter} with the raw value. Render a template with a hostile name and a trusted HTML snippet.

Exercise 9: stop SQL injection. Given a search by customer last name, write a vulnerable version that builds the SQL by concatenation and a safe version with a prepared statement. Run both with x' OR '1'='1 as the name.

Exercise 10: a translator with fallback. Implement trans($key, $params, $locale). Look in the requested locale first, then in the default locale, and finally return the key. Replace %name%-style placeholders.

PHP Solutions 8, 9 and 10: escape, SQL, translate

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 vulnerable query returns every customer because the quote in the input closes the string and OR '1'='1' is always true. The prepared statement treats the whole attack text as one name and finds nothing. In real PrestaShop code the rule is the same: use pSQL() for strings and integer casts for numbers when you build strings with the Db class, and prefer queries where data is never mixed into SQL text.

How to use these exercises

  1. Write your own solution before reading mine. Struggling for ten minutes teaches more than reading.
  2. Change one rule and predict the output: add a fourth listener, allow http URLs, add a locale.
  3. Then translate each exercise to real PrestaShop on a local test shop: the hook dispatcher becomes Hook::exec, the entity becomes an ObjectModel, the router becomes a ModuleFrontController, and the translator becomes $this->trans().
  4. Keep a note of where the stand-in is simpler than the real thing. Knowing the gaps is part of the skill.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why must an action hook listener receive its parameters by reference?

    Action hooks signal events and let modules adjust data. Changing the array in place is how one listener's change reaches the next.
  2. 2. Why can sorting upgrade file names alphabetically be a bug?

    Text order is not version order. version_compare understands the numeric parts.
  3. 3. What does a prepared statement change in the SQL injection exercise?

    The structure of the query is fixed first and the value is sent separately, so quotes in the input cannot change the query.
  4. 4. In the escaping exercise, when is a nofilter style output acceptable?

    Raw output is acceptable for HTML you built yourself. Anything a user can influence must be escaped.

Summary

  • Display hooks concatenate output in position order; action hooks pass data by reference, so order can change results.
  • Validate settings on the server, save only complete valid sets, and keep old values otherwise.
  • An entity definition drives validation and saving; invalid objects must never reach the database.
  • Compare versions with version_compare, not string sorting.
  • Answer requests with correct status codes, verify tokens in constant time, escape output by default and keep data out of SQL text.

Continue with PrestaShop Interview Questions.