Skip to content

Create custom product code generator strategy

Product code generator strategies control what product variant codes are generated.

Besides the built-in strategies, you can create your own ones.

A code generator strategy must implement Ibexa\Contracts\ProductCatalog\Local\CodeGenerator\CodeGeneratorInterface.

The following example shows how to add a generator strategy that creates code, based on the product base code and an incremental index number.

First, create the generator strategy class:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
<?php

declare(strict_types=1);

namespace App\CodeGenerator\Strategy;

use Ibexa\Contracts\Core\Exception\InvalidArgumentException;
use Ibexa\Contracts\ProductCatalog\Local\CodeGenerator\CodeGeneratorContext;
use Ibexa\Contracts\ProductCatalog\Local\CodeGenerator\CodeGeneratorInterface;

final class CustomIncrementalCodeGenerator implements CodeGeneratorInterface
{
    public function generateCode(CodeGeneratorContext $context): string
    {
        if (!$context->hasBaseProduct()) {
            throw new InvalidArgumentException('$context', 'missing base product');
        }

        if (!$context->hasIndex()) {
            throw new InvalidArgumentException('$context', 'missing index');
        }

        return $context->getBaseProduct()->getCode() . 'v' . $context->getIndex();
    }
}

This generator uses the provided context to get product information (in this case the code of the base product) and the incremental number.

Then, register the strategy generator as a service and tag it with ibexa.product_catalog.code_generator:

1
2
3
4
services:
    App\CodeGenerator\Strategy\CustomIncrementalCodeGenerator:
        tags:
            - { name: 'ibexa.product_catalog.code_generator', type: 'custom_incremental' }

Use the defined type in catalog configuration to apply codes generated by this strategy to new product variants.