Skip to content

Segment API

Segments enable you to profile the content displayed to specific users.

To manage Segments, use the SegmentationService.

Getting Segment information

To load a Segment Group, use SegmentationService::loadSegmentGroupByIdentifier(). Get all Segments assigned to the group with SegmentationService::loadSegmentsAssignedToGroup():

1
2
3
4
5
6
7
        $segmentGroup = $this->segmentationService->loadSegmentGroupByIdentifier('custom_group');

        $segments = $this->segmentationService->loadSegmentsAssignedToGroup($segmentGroup);

        foreach ($segments as $segment) {
            $output->writeln('Segment ID: ' . $segment->id . ', name: ' . $segment->name);
        }

Similarly, you can load a Segment by using SegmentationService::loadSegmentByIdentifier():

1
        $segment = $this->segmentationService->loadSegmentByIdentifier('segment_1');

Checking assignment

You can check whether a User is assigned to a Segment with SegmentationService::isUserAssignedToSegment():

1
2
3
4
5
        $output->writeln((
            $this->segmentationService->isUserAssignedToSegment($user, $segment)
            ? 'The user is assigned to the segment.'
            : 'The user is not assigned to the segment.'
        ));

Assigning Users

To assign a User to a Segment, use SegmentationService::assignUserToSegment():

1
        $this->segmentationService->assignUserToSegment($user, $segment);

Creating Segments

Each Segment must be assigned to a Segment Group.

To create a Segment Group, use SegmentationService::createSegmentGroup() and provide it with a SegmentGroupCreateStruct:

1
2
3
4
5
6
7
        $segmentGroupCreateStruct = new SegmentGroupCreateStruct([
            'name' => 'Custom Group',
            'identifier' => 'custom_group',
            'createSegments' => [],
        ]);

        $newSegmentGroup = $this->segmentationService->createSegmentGroup($segmentGroupCreateStruct);

To add a Segment, use SegmentationService::createSegment() and provide it with a SegmentCreateStruct, which takes an existing group as one of the parameters:

1
2
3
4
5
6
7
        $segmentCreateStruct = new SegmentCreateStruct([
            'name' => 'Segment 1',
            'identifier' => 'segment_1',
            'group' => $newSegmentGroup,
        ]);

        $newSegment = $this->segmentationService->createSegment($segmentCreateStruct);

Updating Segments

To update a Segment or a Segment Group, use SegmentationService::updateSegment() or SegmentationService::updateSegmentGroup() and provide it with SegmentUpdateStruct or SegmentGroupUpdateStruct, respectively.

Deleting Segments

To delete a Segment or a Segment Group, use SegmentationService::removeSegment() or SegmentationService::removeSegmentGroup(), respectively:

1
$this->segmentationService->removeSegmentGroup($group);