Skip to content
Tutorials Center
My learning

Topics

Lesson 14 of 30 ยท ObjectModel and Data

Working with Products, Carts and Orders

Read and change products, carts, orders, customers and addresses from a PrestaShop module: price and tax helpers, order states and safe practices, with stand-ins.

Almost every module touches the same few things: the product on a page, the cart a customer is filling, the order that was just placed, the customer behind it. PrestaShop gives each of them a class (Product, Cart, Order, Customer, Address), all built on ObjectModel. Knowing which class owns which fact, and which methods you should call instead of writing SQL, is what keeps a module correct when the shop has discounts, several currencies and tax rules.

This lesson is a tour of those classes from a module author's point of view: how to load them, what the price fields really mean, how order states work and which habits are safe. The real calls are shown as read-only code. The runnable stand-ins show the ideas that matter most: tax and rounding on integer money, and an order that moves through states with a history. The theory behind them lives in the e-commerce track: taxes and the order lifecycle.

Loading entities

Every one of these classes is loaded by passing an id to the constructor. Classes with translatable fields also take a language id.

PHP
// read-only examples
$product  = new Product((int) $idProduct, false, (int) $this->context->language->id);
$customer = new Customer((int) $idCustomer);
$address  = new Address((int) $idAddress);
$order    = new Order((int) $idOrder);

if (!Validate::isLoadedObject($product)) {
    // the id does not exist: never assume the load worked
    return;
}

Validate::isLoadedObject() is the standard check. A constructor with an unknown id does not throw; it returns an object whose id is empty. Skip the check and you will read fields from an empty object.

The third argument matters for names. Without a language id, $product->name is an array indexed by language id; with one, it is a plain string. If you see "Array to string conversion" in a template, this is almost always why.

To read many objects, use a PrestaShopCollection (it lazily loads objects from a query) instead of one new per row, or ask a static helper that already runs a single query.

The cart and the context

Shoppers do not reach a cart by id. The cart that belongs to the current visitor sits in the context:

PHP
$cart = $this->context->cart;           // Cart or null
$customer = $this->context->customer;   // always an object, may be a guest
$currency = $this->context->currency;

In front office hooks you often get the cart in the hook parameters ($params['cart']). Prefer that, and fall back to the context. A visitor who has not added anything may have no cart yet, so test it before use.

Useful Cart methods:

  • $cart->getProducts() returns the lines with quantities, prices and ids.
  • $cart->getOrderTotal(true, Cart::BOTH) returns the total with taxes (true) for products, shipping and wrapping. Pass false for tax-excluded. Cart::ONLY_PRODUCTS and Cart::ONLY_SHIPPING restrict what is counted.
  • $cart->updateQty($quantity, $idProduct, $idProductAttribute) changes a line and applies stock and rule checks; do not write rows into the cart table yourself.
  • $cart->id_customer, id_address_delivery, id_address_invoice and id_currency link the cart to the customer, addresses and currency.

getOrderTotal() is the right way to get what the customer pays, because it includes cart rules, shipping and the taxes of the delivery country. If you recompute the total yourself from line prices you will drift from the real number the first time a discount applies.

Product prices

The base price stored on a product is tax excluded. A tax rule group decides which rate applies, depending on the customer's address; specific prices, groups and cart rules can lower the final amount. So $product->price is rarely what a shopper sees. Ask the price calculation:

PHP
// read-only examples
$withTax   = Product::getPriceStatic($idProduct, true);   // tax included
$withoutTax = Product::getPriceStatic($idProduct, false); // tax excluded

Product::getPriceStatic() has many optional parameters (combination, quantity, whether to include specific prices and so on), and it uses the context for the customer, group and country. Read the signature of the version you target, and pass the combination id when the product has variants.

Display amounts with the locale of the context, not with number_format():

PHP
// read-only: formatting depends on the PrestaShop version; check yours
$label = $this->context->getCurrentLocale()->formatPrice(
    $withTax,
    $this->context->currency->iso_code
);

Tools::ps_round() rounds to the shop's precision. Older code used Tools::displayPrice(), which is deprecated in recent versions.

Stock lives in its own class. Read it with StockAvailable::getQuantityAvailableByProduct($idProduct, $idProductAttribute) and change it with StockAvailable::updateQuantity(), never by editing the product row. See inventory basics for the ideas behind it.

Customers and addresses

Customer holds the account: names, email, group, newsletter flag, password hash. Look a customer up by email with Customer::getByEmail($email), which returns a loaded Customer or false. Never read or write the password field yourself.

Address holds a postal address and is linked to a country (id_country), which drives tax and shipping. A customer has several addresses; orders point to one for delivery and one for invoicing and keep them by id. Customers can edit or delete addresses, and PrestaShop keeps order addresses intact by flagging deleted addresses rather than removing them. For a module this means: when you show an order's address, load it by the id stored on the order, not by "the customer's current address".

Orders and order states

An order is created when payment is validated. A payment module calls validateOrder() (see Payment Modules); ordinary modules should not create orders by hand. Once it exists, you read it with the Order class:

PHP
// read-only examples
$order = new Order((int) $idOrder);

$reference = $order->reference;                 // e.g. "KHWLILZLL"
$paidWithTax = $order->total_paid_tax_incl;     // what the customer paid
$paidWithoutTax = $order->total_paid_tax_excl;
$lines = $order->getProducts();                 // order lines (a snapshot)
$stateId = (int) $order->getCurrentState();

Order lines are a snapshot: the price and name at the time of purchase, stored on the order. Changing the product later does not change old orders, which is exactly what accounting needs.

Amounts are stored as decimals (six decimal places in the database) and rounded for display, so compare totals with a small tolerance or in integer units, never with == on floats.

Order states

Each order has a current order state, such as "Awaiting payment", "Payment accepted", "Processing in progress", "Shipped", "Delivered", "Canceled" or "Refunded". States are rows in a table that merchants can edit and extend, and each state carries flags such as paid, shipped, delivery and logable (counts as a valid sale in statistics). The shop's main states are referenced through configuration keys, for example PS_OS_PAYMENT, PS_OS_SHIPPING, PS_OS_DELIVERED, PS_OS_CANCELED and PS_OS_REFUND:

PHP
$paymentAccepted = (int) Configuration::get('PS_OS_PAYMENT');

Never hard-code a state id; ids differ between shops, and merchants can add their own states. Look it up through the configuration key, or select states by flag.

You change the state with an OrderHistory object, which records who changed it and when, and fires the related hooks and emails:

PHP
// read-only
$history = new OrderHistory();
$history->id_order = (int) $order->id;
$history->id_employee = (int) ($this->context->employee->id ?? 0);
$history->changeIdOrderState((int) Configuration::get('PS_OS_SHIPPING'), $order);
$history->addWithemail();   // saves the history row and sends the state's email

Skipping OrderHistory and updating current_state in SQL leaves the history empty, no emails go out, stock actions are skipped and other modules listening for status changes never hear about it. PrestaShop does not ship a strict graph of allowed transitions; the back office lets an employee choose most states. If your business needs rules ("never ship an unpaid order"), enforce them in your own code.

stateDiagram-v2
    [*] --> AwaitingPayment
    AwaitingPayment --> PaymentAccepted: "payment confirmed"
    AwaitingPayment --> Canceled: "customer or admin cancels"
    PaymentAccepted --> Processing
    Processing --> Shipped
    Shipped --> Delivered
    PaymentAccepted --> Refunded
    Delivered --> Refunded

A typical order journey. The states are data, so a real shop can have more, and the arrows are a convention, not a restriction built into the core.

Safe read and write practices

  1. Use the class API, not SQL, for writes. Cart, Order, OrderHistory and StockAvailable do much more than store a row: hooks, caches, stock, emails.
  2. Read in bulk. Loading orders in a loop with new Order($id) runs several queries per iteration. Use a PrestaShopCollection or one query with Db::getInstance()->executeS() when you need lists, as discussed in Performance and Caching.
  3. Check what you loaded with Validate::isLoadedObject().
  4. Respect the shop and language context. Pass the language id; remember that in multistore, data can differ per shop.
  5. Keep money in integers when you calculate. Convert decimals to the smallest unit, compute, then convert back. See money as integers.
  6. Never trust ids from the request. A customer must only see their own orders: compare $order->id_customer with the logged-in customer before showing anything.
  7. Snapshots are history. Do not "fix" old order lines to match new prices.

Tax and rounding, with integers

Tax is where small mistakes become real money. The shop setting for rounding decides whether the tax is rounded per item, per line or on the total, and the three can differ by a cent or more. The stand-in below uses integer cents and basis points (2000 means 20.00 percent), and compares the three modes. It is a model of the idea, not PrestaShop's own calculator, which also handles tax rule groups, several taxes on one product and cart rules.

PHP Stand-in: tax rounding per item, per line and on the total

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.

Look at the individual lines: the notebook line costs 12.00 when each unit is rounded and 11.99 when the line is rounded. Here the item and line modes happen to agree on the grand total (31.65), while rounding the total once gives 31.64: a cent of difference on a small basket, more on a big one. This is why you should use the cart's own getOrderTotal() rather than adding your own numbers, and why your module should never compare a total of its own against the shop's.

An order and its history

The second stand-in models the order, the state table with flags and the history, using SQLite. Changing state goes through one function, like OrderHistory does in the real system: it refuses a change to the state the order already has, writes a history row, updates the current state and reports what the flags mean. The "do not ship an unpaid order" rule is our own addition for the demo; it shows where your business rule would live.

PHP Stand-in: order states with flags and a history table

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.

What is real here and what is not: the flags, the state lookup by configuration key, the history rows and the "same state is refused" behavior mirror how PrestaShop works. The blocking of a shipment without payment is ours, and the real OrderHistory additionally manages stock, invoices, emails and hooks.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does $product->price hold?

    The stored price is the tax-excluded base price. Use Product::getPriceStatic() or the cart total to get what the shopper actually pays.
  2. 2. Why should a module change an order's state with OrderHistory instead of updating current_state in SQL?

    A direct SQL update skips the history row, the state's email, stock actions and the hooks other modules listen to, so the shop ends up inconsistent.
  3. 3. Which is the safe way to refer to the 'Payment accepted' state?

    State ids differ between shops and merchants can add or rename states. The configuration keys point to the right row on every shop.
  4. 4. A new Product loaded without a language id: what is $product->name?

    Without a language id the multilingual fields are arrays keyed by language. With an id, they are plain strings.
  5. 5. Order lines in an old order show a different price than the product page today. What is correct?

    Orders keep the price and name as they were at purchase. Changing them would falsify the shop's records.

Summary

  • Load entities by id, check them with Validate::isLoadedObject(), and pass a language id to get strings instead of arrays.
  • The current cart comes from the context or hook parameters; use getOrderTotal() for totals instead of recomputing.
  • Stored product prices are tax excluded; ask Product::getPriceStatic() for what a customer pays and format with the context's locale.
  • Orders are snapshots; states are editable data with flags, referenced by configuration keys, changed through OrderHistory.
  • Use the class API for writes, bulk reads for lists, integer money for your own calculations, and check ownership before showing customer data.

Next: The Symfony Back Office