Skip to content
Tutorials Center
My learning

Topics

Lesson 6 of 28 ยท Controllers, Models and Templates

Models, Decorators and Helpers

Learn how SFRA shapes platform objects into models: constructors, the decorator pattern, ProductFactory, helpers, and when code belongs in scripts or models. Includes runnable demos.

Platform objects such as dw.catalog.Product or dw.order.Basket are rich, but they are awkward to hand to a template. They expose many methods, they can throw on missing data, and every call into them costs time. SFRA solves this with models: plain JavaScript objects that contain exactly the fields a page needs, already formatted. Controllers build a model and pass it to the template as pdict.product, and the template never touches the platform API directly.

This lesson explains how models are built, the decorator pattern SFRA uses for products, the factory that picks the right pieces, and where helper code belongs. It connects the controllers from Controllers, Routes and Middleware with the templates in ISML Templates.

The model code in this lesson is plain JavaScript but depends on platform classes (dw/catalog/...), so it is shown read-only. The runnable examples are stand-ins that use a fake product object and recreate the decorator pattern. They are simplified compared to SFRA's real product models.

Why models exist

A model has three jobs:

  1. Isolate templates from the Script API, so a template can change without touching data code.
  2. Shape data: format a price as text, pick the first image, compute a label.
  3. Be safe to serialize: models are often sent as JSON to the browser, so they must contain plain values, not live platform objects.

In SFRA, models live in cartridge/models/ and are constructed by controllers or by factories. A simple model is just a constructor:

JavaScript
// Read-only: a small model (cartridge/models/shippingMethod.js, simplified)
'use strict';

function ShippingMethodModel(shippingMethod, shipment) {
    this.ID = shippingMethod.ID;
    this.displayName = shippingMethod.displayName;
    this.description = shippingMethod.description;
    this.selected = Boolean(shipment && shipment.shippingMethodID === shippingMethod.ID);
}

module.exports = ShippingMethodModel;

A controller or helper calls new ShippingMethodModel(apiObject, shipment), and the result goes to the template.

The decorator pattern

Products are the hard case. A product tile needs a name, price and one image. A product detail page needs a name, price, all images, variation attributes, availability, promotions and more. Writing one giant product model wastes time on tiles; writing many separate models duplicates code.

SFRA's answer is decorators. Each decorator is a small function that adds one group of properties to an object:

JavaScript
// Read-only: a decorator (models/product/decorators/base.js, simplified)
'use strict';

module.exports = function (object, apiProduct) {
    Object.defineProperty(object, 'id', {
        enumerable: true,
        value: apiProduct.ID
    });
    Object.defineProperty(object, 'productName', {
        enumerable: true,
        value: apiProduct.name
    });
};

A model for a given purpose is built by applying the decorators it needs. The tile applies a few, the full product page applies more:

JavaScript
// Read-only: composing a model from decorators
var base = require('*/cartridge/models/product/decorators/base');
var price = require('*/cartridge/models/product/decorators/price');
var images = require('*/cartridge/models/product/decorators/images');

function ProductTile(apiProduct) {
    var product = {};
    base(product, apiProduct);
    price(product, apiProduct);
    images(product, apiProduct);
    return product;
}

Why this design?

  • Reuse without inheritance. Any combination of decorators is possible.
  • Easy extension. A project can add a decorator (say, a delivery label) in its own cartridge without editing the base models.
  • Defined properties are read-only and enumerable, so they serialize into JSON but cannot be accidentally overwritten by a template or script.
flowchart LR
    P["dw Product<br/>(platform object)"] --> D1["base decorator"]
    P --> D2["price decorator"]
    P --> D3["images decorator"]
    D1 --> M["Model object<br/>(plain values)"]
    D2 --> M
    D3 --> M
    M --> T["ISML template<br/>pdict.product"]

Each decorator copies one slice of the platform object into the model.

JS The decorator pattern with a fake product (stand-in)

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The tile model has only four keys, while the detail model has six. A page that lists forty products builds forty tiles, so every unnecessary property you skip saves real work.

Factories choose the recipe

A controller should not decide which decorators to apply. SFRA uses a factory. ProductFactory.get(params) loads the platform product, looks at its type and the requested view (tile, quick view, full page) and calls the right model constructor.

JavaScript
// Read-only: how a controller uses the factory
var ProductFactory = require('*/cartridge/scripts/factories/product');

var product = ProductFactory.get({
    pid: req.querystring.pid,
    pview: 'tile'   // or 'productDetail'
});

Because the controller requires the factory with */cartridge/..., a project can override the factory in its overlay cartridge to add a new product type or view without touching controllers.

JS A product factory and a helper (stand-in)

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The controller knows only ProductFactory.get. Adding a new product type means adding one recipe, which is why this structure survives years of project changes.

Helpers and scripts

Not everything is a model. SFRA keeps several folders with different purposes:

Folder Holds Example
models/ Constructors and decorators that build page data models/product/productTile.js
scripts/helpers/ Reusable functions grouped by domain productHelpers, cartHelpers
scripts/factories/ Choose which model to build scripts/factories/product.js
scripts/hooks/ Functions registered for hooks scripts/hooks/payment/processor/basic_credit.js
scripts/util/ Small shared utilities collection helpers

A practical rule: if it builds data for the view, it is a model or decorator. If it does work (update a basket, call a service, calculate shipping), it is a helper. Keep helpers free of req and res where you can, so they are easy to test (see Testing, Debugging and Logging).

Real helpers often render templates to a string, for example for an email or an AJAX response that includes HTML. SFRA wraps this in a helper that uses the platform's template class. Check the helper in your base cartridge rather than writing your own, and pass it only plain data.

A few cautions:

  • Do not put live platform objects in a model that you serialize. Copy the values you need.
  • Be careful with collections. Script API collections are not JavaScript arrays. Convert them (SFRA includes a collections helper with map, forEach and find) before using array methods.
  • Do work once. If tile building runs a promotion lookup per product, a category page pays for it forty times. Look at the performance chapter before adding decorators to tiles.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is the main purpose of an SFRA model?

    Models isolate templates from the Script API and hold only the values a view needs.
  2. 2. Why use decorators instead of one big product model?

    Composition avoids duplication and over-fetching, and extension means adding a decorator without editing the base models.
  3. 3. What does a factory such as ProductFactory.get decide?

    The controller only asks for a product. The factory picks the right recipe by type and requested view.
  4. 4. A helper that updates a basket and does not need req or res is best placed in...

    Work-doing code belongs in helpers, where it can be reused and tested without a request.
  5. 5. Why is Object.defineProperty with enumerable true used in decorators?

    Enumerable properties serialize; without a setter or writable flag they cannot be overwritten accidentally.

Summary

  • Models are plain objects that hold exactly the data a template needs, built by constructors or decorators.
  • Decorators add one group of properties each; compose them for tiles, detail pages and other views.
  • Factories such as ProductFactory choose the recipe so controllers stay thin and extendable.
  • Models shape data; helpers do work; keep platform objects and collections out of serialized models.
  • The cartridge path lets a project override a factory, decorator or helper without editing the base.

Next: ISML Templates