Home Web Development Practical Module development for Prestashop 8

Practical Module development for Prestashop 8

By Louis AUTHIE
ai-assist-svg-icon Book + AI Assistant
eBook + AI Assistant $27.99 $18.99
Print $34.99
Subscription $15.99 $10 p/m for three months
ai-assist-svg-icon NEW: AI Assistant (beta) Available with eBook, Print, and Subscription.
ai-assist-svg-icon NEW: AI Assistant (beta) Available with eBook, Print, and Subscription. $10 p/m for first 3 months. $15.99 p/m after that. Cancel Anytime! ai-assist-svg-icon NEW: AI Assistant (beta) Available with eBook, Print, and Subscription.
What do you get with a Packt Subscription?
Gain access to our AI Assistant (beta) for an exclusive selection of 500 books, available during your subscription period. Enjoy a personalized, interactive, and narrative experience to engage with the book content on a deeper level.
This book & 7000+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats, plus a monthly download credit
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
Gain access to our AI Assistant (beta) for an exclusive selection of 500 books, available during your subscription period. Enjoy a personalized, interactive, and narrative experience to engage with the book content on a deeper level.
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Along with your eBook purchase, enjoy AI Assistant (beta) access in our online reader for a personalized, interactive reading experience.
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with video?
Stream this video
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
What do you get with Exam Trainer?
Flashcards, Mock exams, Exam Tips, Practice Questions
Access these resources with our interactive certification platform
Mobile compatible-Practice whenever, wherever, however you want
ai-assist-svg-icon NEW: AI Assistant (beta) Available with eBook, Print, and Subscription. ai-assist-svg-icon NEW: AI Assistant (beta) Available with eBook, Print, and Subscription. BUY NOW $10 p/m for first 3 months. $15.99 p/m after that. Cancel Anytime! ai-assist-svg-icon NEW: AI Assistant (beta) Available with eBook, Print, and Subscription.
eBook + AI Assistant $27.99 $18.99
Print $34.99
Subscription $15.99 $10 p/m for three months
What do you get with a Packt Subscription?
Gain access to our AI Assistant (beta) for an exclusive selection of 500 books, available during your subscription period. Enjoy a personalized, interactive, and narrative experience to engage with the book content on a deeper level.
This book & 7000+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats, plus a monthly download credit
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
Gain access to our AI Assistant (beta) for an exclusive selection of 500 books, available during your subscription period. Enjoy a personalized, interactive, and narrative experience to engage with the book content on a deeper level.
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Along with your eBook purchase, enjoy AI Assistant (beta) access in our online reader for a personalized, interactive reading experience.
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with video?
Stream this video
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
What do you get with Exam Trainer?
Flashcards, Mock exams, Exam Tips, Practice Questions
Access these resources with our interactive certification platform
Mobile compatible-Practice whenever, wherever, however you want
  1. Free Chapter
    Chapter 1: Quick Overview of PrestaShop
About this book
After version 1.7, PrestaShop underwent a host of changes, including migration to a Symfony-based system from an outdated legacy code. This migration brought about significant changes for developers, from routine maintenance to module development. Practical Module Development for PrestaShop 8 is curated to help you explore the system architecture, including migrated and non-migrated controllers, with a concise data structure overview. You’ll understand how hooks enable module customization and optimize the CMS. Through the creation of seven modules, you’ll learn about the structure of modules, hook registration, the creation of front-office controllers, and Symfony back-office controllers. By using Doctrine entities, services, CQRS, grids, and forms, you’ll be guided through the creation of standard, payment and carrier modules. Additionally, you'll customize and override themes to achieve your desired e-commerce store look. By the end of this book, you’ll be well equipped to provide modern solutions with PrestaShop that meet client requirements.
Publication date:
April 2023
Publisher
Packt
Pages
300
ISBN
9781837635962

 

Quick Overview of PrestaShop

Having set up PrestaShop (please see https://devdocs.prestashop-project.org/1.7/basics/installation/, if you haven’t) and used it, you may know the two main parts of it. As with other content management systems (CMSs) such as WordPress, there’s a public part unrestricted and visible by any visitor of your website named the Front Office (FO), and there’s a restricted part, only visible by employees with email and password authentication, called the Back Office (BO).

In this chapter, we will explain quickly how everything is designed, from the database to the core structure of the FO and the BO, and how they are linked.

In this chapter, we will cover the following main topics:

  • The data model—how and where data is stored
  • The core classes—how the Model-View-Controller (MVC) works

By the end of this chapter, you will know how the database is built, the types of tables, and how the core manages and manipulates entities. You will understand, from a high-level point of view, the MVC structure of FO and BO pages and how some BO pages are being migrated from the legacy-based core to a Symfony-based one.

 

Technical requirements

As we will explore the environment of PrestaShop to understand how everything is articulated, you will have to use some tools to do mainly reverse engineering:

  • phpMyAdmin or other MySQL database clients such as Adminer
  • Any PHP code editor
  • A (Secure) File Transfer Protocol ((S)FTP) client to browse your website files (only if you work on a remote server—not necessary if you work on a local server)
 

The data model–how and where data is stored

Let’s start this journey into PrestaShop by presenting how data is stored.

Data is all mutable information stored on the server to make the shop work, such as product information, customer details, orders, category information, employee settings, and so on.

All this information is stored in a MySQL database on the server. You may already know this because you have been requested to provide the database details to access the MySQL database during the installation steps.

Let’s browse the data to see how it works.

Browsing the data

To browse all the data stored in the PrestaShop database, please follow these steps:

  1. Connect to the database created for your PrestaShop with your favorite database client such as phpMyAdmin.
  2. Show all tables.

There, you will see a list of all tables, named following these patterns:

  • prefix_nameofentity (for example, ps_cms and ps_access):

All entities should use the prefix_nameofentity table name to store all non-localized data, without any restrictions on the number of columns. The first column for those tables is always the unique ID (UID) of each row, and its name always follows the same pattern: id_nameofentity. This is useful for creating relationships with other entities and makes data management easier.

  • prefix_nameofentity_lang (for example, ps_cms_lang and ps_carrier_lang):

If an entity has localizable data, you should use another table called prefix_nameofentity_lang to store fields depending on the user’s language.

It should represent a many-to-many relationship between the prefix_nameofentity table and prefix_lang table that contains all available languages in your PrestaShop platform. That’s why you will always find an id_nameofentity column to represent the link with the prefix_nameofentity table and an id_lang column to represent the link with the prefix_lang table. These tables are not mandatory if you don’t have localized data to store.

  • prefix_nameofentity_shop (for example, ps_cms_shop and ps_product_shop):

If an entity is shop-dependent (in the context of a multistore website, as PrestaShop makes this possible), you will find another table called prefix_nameofentity_shop. It represents a many-to-many relationship between the prefix_nameofentity table and the ps_shop table containing all available stores created in your PrestaShop platform. Exactly the same way as _lang tables do, you will always find an id_nameofentity column to represent the link with the prefix_nameofentity table and an id_shop column to represent the link with the prefix_shop table. These tables are only present if you want to make your entity multistore compliant.

What are prefix_ and nameofentity?

prefix_ is a string that is set during the installation process, in the database details step, and by default, it’s set to ps_, but you may have chosen a different one.

In the rest of the book, we will assume that you chose ps_ as a prefix.

nameofentity stands for the name of the entity stored. For example, for products, the name of the entity is product; that’s why you should find a ps_product table in the database!

Reverse engineering the contact entity

The contact entity contains all information about the recipients of contact queries done through the Contact us page of your store. You can put as many recipients of services as you need. Usually, there are two of them automatically set: one for technical queries and the other for customer/sales queries.

The best way to understand how things work is by doing reverse engineering. So, let’s explore how the contact entity is built in the database. By browsing the tables list, considering that our prefix is set to ps_, you will find three tables corresponding to the contact entity:

  • The ps_contact table:

Name

Type

Extra information

id_contact

Int(10)

Auto_increment

email

Varchar(255)

customer_service

TinyInt(1)

position

TinyInt(2)

Table 1.1 – The ps_contact table

This table contains all universal, non-translatable fields about contact information: the email address, a flag (true=1/false=0) to inform the system if the recipient provides customer service, and the position for the display order on the contact form. Please note that there is always a key column following the id_nameofentity pattern in entities. It is auto-incrementing and set as the primary key. It enables us to identify and manipulate rows easily. It is also mandatory if we have to create a many-to-one relationship with this table.

  • The ps_contact_lang table:

Name

Type

Extra information

id_contact

Int(10)

id_lang

Int(10)

name

Varchar(255)

description

Text

Table 1.2 – The ps_contact_lang table

This table contains all localizable data languages linked. It is used to provide translated content to the system. For the contact entity, there are only two fields requiring localization: the name field, designating the recipient of contact queries, and the description field, explaining the function of the recipient. This table materializes the many-to-one relationship with ps_contact, as there are many translations for only one contact. The id_contact column is used to map translations with the corresponding ps_contact rows. The id_lang column is used to map translations with the corresponding languages (1 for English, 2 for French, and so on, depending on your settings).

  • The ps_contact_shop table:

Name

Type

Extra information

id_contact

Int(11)

id_shop

Int(11)

Table 1.3 – The ps_contact_shop table

This table represents the many-to-many relationship between the ps_contact entity and the ps_shop entity. It links contacts to the store in which they are available to customers/visitors. The id_contact column stands for the linked contact, and id_shop stands for the shop where the corresponding contact is available.

As you may have seen, the tables are not linked by foreign keys, which would be normal with a many-to-many relationship, but in PrestaShop, this is not the case yet.

You now know with this example how things are linked and stored together in the database.

Tip

If you want to inspect the whole structure and the links between tables, the structure is available during the installation process—that is, if you have not yet removed the install folder (which is recommended), at this path: /install/data/db_structure.sql.

Now that you know how and where data is stored in the database, let’s see where and how entities are coded in PHP in order to manage them.

Manipulating data by extending the ObjectModel class

PrestaShop is a set of PHP files, templates, and assets (such as images, JavaScript, or style sheets) working together to generate an e-commerce system.

Specifically, inside the PHP files, in the /classes/ObjectModel.php folder, you will find the definition of the ObjectModel class, which implements the EntityInterface interface defined in the /src/Code/Foundation/Database/EntityInterface.php folder with these methods:

public static function getRepositoryClassName();
public function save();
public function delete();
public function hydrate(array $keyValueData);

Almost all entities of the system extend this ObjectModel class, which contains all the necessary tools to manipulate the entity.

Practically, all entities’ definitions are PHP classes defined in /classes/NameOfEntity.php. Feel free to open some of the files to see how they work.

If you come back to the ObjectModel class, you will see that it contains a property named $definition. This is an array that will contain all metadata fields and properties of the entity. It has to follow this prototype:

public static $definition = [
    'table' => 'nameofentity',
    'primary' => 'id_nameofentity',
    'multilang' => true,//if not localizable set to false
    'multishop' => true,//if not multistore set to false
  //'multilang_shop' => true, 
  //can replace both previous fields set to true
    'fields' => array(
        'id_nameofentity'  => ['type' => self::TYPE_INT,
            'validate' => 'isUnsignedInt'],
        'field_name'           => ['type' => ... ],
     ....)
];

Member variables have to be defined to represent each field that will be hydrated with their value. For example, if you have a field named field_name in the database, it has to be added to the entity class, like this:

public $field_name;

As seen before, to comply with the EntityInterface interface, we have to implement the three following methods:

  • The save() method implements, in the database, the insertion or updates of the row represented by the current entity instance
  • The delete() method removes the current row
  • The hydrate() method sets the member variables of the current instance in order to be able to use the object

Practically, after having defined an entity with the creation of its class, everywhere in the code of PrestaShop, we will be able to create a new instance of it by using this:

//To create an empty instance of NameOfEntity
$entityInstance = new NameOfEntity();

If you want an entity to be instanced and hydrated with the values of the row with id_nameofentity equal to $value_id_nameofentity, you can use this code:

/* To create a hydrated instance of NameofEntity with id_nameofentity=$value_id_nameofentity */
$entityInstanceHydrated = new NameOfEntity((int) $value_id_nameofentity);

Try this

As a practical exercise, try to open one of the classes defined in the /classes folder.

Using the Db class

As you may have seen by opening some classes of the /classes folder, the ObjectModel child class uses the Db class defined in the /classes/db/Db.php file to work with the database’s low-level actions, such as insert, update, and delete. We won’t dive deeply into this class—you just have to remember that you can use this class anywhere with the following methods. In this method, we’ll instantiate the Db class to use its functions:

/*Instantiate the Db class in order to be able use its functions*/
$db = \Db::get Instance();

The following are the SELECT methods:

/*To do a select query with _DB_PREFIX_ a constant that contains the prefix for tables*/
$select_query = 'SELECT * FROM `' . _DB_PREFIX_ . 'nameofentity` WHERE 1';
$result = $db->executeS($select_query);
/*To get the first line of the results as an array */
$select_query = "SELECT `id_nameofentity`, `field_name` FROM `' . _DB_PREFIX_ . 'nameofentity` WHERE 1";
$result = $db->getRow($request);

The following code can be used to insert, update, and delete and for custom query methods:

/*To insert row(s) with pSQL() a function to avoid SQL injections or other threats*/
$result = $db->insert('nameofentity ',
    [
        //First row
        [
            'field_name' => pSQL('field_value'),
            'field_name' => pSQL('field_value'),
        ],
        //Second row
        [
            'field_name' => pSQL('field_value'),
            'field_name' => pSQL('field_value'),
        ]
    ]
);
/*To update row with id_nameofentity=2*/
$result = $db->update('nameofentity', [
    'field_name' => pSQL('field_value'),
    'field_name' => pSQL('field_value'),
], 'id_nameofentity = 2', 1, true);
/*To delete row with id_nameofentity=2*/
$result = $db->delete('nameofentity', 'id_nameofentity = 2');
/*To execute a raw custom query*/
$sql_query = "UPDATE `' . _DB_PREFIX_ . 'nameofentity`  SET ` field_name `= 3 WHERE `id_nameofentity `=2";
$result = $db->execute($sql_query);

Important note

The way of managing data by using the ObjectModel extension is a bit old-fashioned. As PrestaShop is being migrated to a Symfony-based core, the target is to use the Doctrine library for all entities as soon as the migration is finished.

Currently, while the migration is still a work in progress, most entities are still using ObjectModel to manage the database interfaces, as illustrated in the following diagram:

Figure 1.1 – The data management process in PrestaShop

Figure 1.1 – The data management process in PrestaShop

Now that we know how the data is stored and can be manipulated, we need to understand how FO and BO pages are generated by PrestaShop.

 

The core classes – how the MVC works

Let’s explore how pages are generated by PrestaShop. Don’t worry if you think that we won’t go deep enough into how everything works; we want to stay in a high-level point of view to get a full picture of the system. In Chapters 3 and 4, we will be more technical!

FO and BO pages are automatically generated by the core of PrestaShop. As with many existing CMSs, PrestaShop uses a custom PHP framework that was improved following the versions. This original framework built from the beginning to version 1.7.x.x is called the legacy core by the developers of the PrestaShop community. It is still improving to cope with the immediate needs of users, but the choice was made by the core developers to move to a new framework based on Symfony.

As it is a strong and efficient framework, it can take care of all the main generic needs of the system, such as security, database handling, and forms generation, and all the most useful tools it provides. It should enable the PrestaShop community to focus on e-commerce-specific needs.

Presenting the legacy core MVC pattern

The legacy core is based on an MVC pattern. If you don’t know this famous design pattern, just remember that each page is generated by a PHP Controller. It uses a Model Object to retrieve or modify data in the database and takes care of all computation and data processing to provide it to a View template. This View template is responsible for the graphical aspect of the page.

It enables the different actors of a project not to interfere. The developers can work on the controller while data managers can take care of the model and the integrators build the views. This way, you can also change each tier of the structure without changing others. Here is a diagram illustrating the same:

Figure 1.2 – The legacy core MVC design pattern

Figure 1.2 – The legacy core MVC design pattern

As presented in Figure 1.2, the Controller calls Object Model(s) to get or manipulate the data, processes it, and sends it to a View template to generate a final view.

\What is the legacy core?

As it is not obvious, the legacy core is a set of PHP classes that are part of the PrestaShop framework. They are mainly stored in the /classes and /controllers folders.

Discovering the core migration

As we have seen before, a migration from the old legacy core to a Symfony-based one is in progress. This migration started with the BO pages and will end with the FO pages. The FO migration will start when the BO has fully migrated. That’s the reason why some BO pages are still using the legacy core MVC and some others use the new Symfony design. All FO pages still use the legacy core before and in the v8.0 release.

You can discriminate which BO pages are migrated by watching their URLs: those containing /index.php?controller=Admin are not migrated yet, and those containing /index.php/ are migrated.

The Symfony migrated pages also use an MVC structure, but they follow the Symfony way of coding by using a different templating engine. Even if Symfony is made to use Doctrine and its entities to manipulate the data, during the migration process, we will still use the ObjectModel child objects we have seen before. The new core of PrestaShop is being built into the /src/ folder. We will see in Chapter 4, The Back Office, how this can be done.

In the following diagram, you will find a summary of how the different pages can be managed during the migration of PrestaShop from Legacy Core to Symfony Core:

Figure 1.3 – How things work during the migration process

Figure 1.3 – How things work during the migration process

The aim of the migration process is to remove Legacy Core and make every page of PrestaShop generated by Symfony Core, as illustrated in the following diagram:

Figure 1.4 – How things will work after the migration process

Figure 1.4 – How things will work after the migration process

Once everything is migrated, every page of the BO and FO will rely on the Symfony core and the full system will be able to use Doctrine entities. This process is likely to spend some years. The full PrestaShop open source project is working on it.

 

Summary

In this chapter, we learned that all data is stored in MySQL tables. There are three types of tables, depending on the localization and the multistore support of each entity. The entities of the core are still stored in the /classes/ folder, and each entity class extends ObjectModel.

We also learned that the Db class must be used to manipulate the data in the database. The core is a set of classes generating the pages of the FO and the BO. The core is MVC pattern-based. The FO and some pages of the BO are using the legacy core. Some BO pages are using the Symfony-based core. The interface with the database is still managed by the ObjectModel child classes during the migration process.

We know now how data is managed, and the design of the core. From a high-level point of view, we know how pages are generated. In the next chapter, we will discover how PrestaShop is initialized both for the FO and the BO, how global variables are set, and how to manually set parameter variables to manage access to the database.

About the Author
  • Louis AUTHIE

    Louis Authie is a freelance full stack developer with over 25 years of experience in PHP. He graduated from the ENAC, Toulouse, France in 2011 as an engineer and from the CNAM Paris, France as an analyst programmer in 2017. Since 2012, he's been developing/maintaining modules and themes from various versions of PrestaShop. Becoming an associate in a label-natural bedding e-shop in 2016 improved his awareness of online sellers' challenges. In 2019, he started contributing to the PrestaShop open-source project, first on documentation, then on back-office migration and bug fixes. Louis also teaches professionals in PHP, WordPress, PrestaShop, and Symfony development as a consultant trainer.

    Browse publications by this author
Practical Module development for Prestashop 8
Unlock this book and the full library FREE for 7 days
Start now