Product Layer Extensions

Question:

When should I extend the Frontastic Domain models such as Frontastic\Common\ProductApiBundle\Domain\Variant and how should I do it?

Answer:

It depends on what you want to do and what properties or features that you're missing. It's possible to extend the Domain Objects like variant, product, etc.

To set the values, you'll need to use our LifecycleDecorators. In these, you can assign the values from the dangerousInner* to the necessary properties, see our API Decorators article for more information.

The dangerousInner* properties will contain all the information that was returned by your commerce Backend. These then get stripped so they're not sent to the Frontend, which is why you need a LifecycleDecorator to enrich your own variant. This is done for performance and security reasons (and also because certain objects aren't possible to encode as JSON).

Below is an example of how you could set a certain property inside a LifecycleDecorator which extends our Product:

class ExtendedProduct extends Product
{
    /**
     * @var string
     */
    public $fancyProperty;
}

use ProductApi\LifecycleEventDecorator\BaseImplementation;
class ProductWithFancyProperty extends BaseImplementation
{
    public function afterGetProduct(
	ProductApi $productApi,
	?Product $product
    ): ?Product {
        return $this->extendProduct($product);
    }

    public function afterQuery(
	ProductApi $productApi,
	?Result $result
    ): ?Result {
        if ($result === null) {
            return null;
        }

        $result->items = array_map(
            function (Product $product) {
                return $this->extendProduct($product);
            },
            $result->items
        );

        return $result;
    }

    public function extendProduct(?Product $product)
    {
        if ($product === null) {
            return null;
        }

        $myExtendedProduct = new ExtendedProduct($product);
        $myExtendedProduct->fancyProperty = $product->variants[0]
                 ->dangerousInnerVariant['attributes']['fancyProperty'];

        return $myExtendedProduct;
    }
}

‹Back

FAQs

Still need help? Contact Us Contact Us