Shopware 6 How do I correctly add an array as extensions to SearchResult

I have multiple working subscriber classes subscribing to ProductListingResultEvent, that add an array as extension to the result.

The code looks something like this:

$myExampleArray = [
    ['key' => 'foobar', 'val1' => 'bar', 'val2' => 'foobarfoo'],
    ['key' => 'barfoo', 'val1' => 'foo', 'val2' => 'barfoobar']
];
$myStructCollection = new StructCollection();
foreach ($myExampleArray as $myExampleElement)
{
    $myStructCollection->set($myExampleElement['key'], $myExampleElement);
}
$event->getResult()->addExtension('myExampleExtension', $myStructCollection);

Is that the right way to do it? Do I always have to instanciate a new Struct to add data as an extension?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

Yes you always have to instantiate a new Struct-Class, as the extension-struct you will add should be independent from the core or other plugins, so they don’t interfere with your logic and may override stuff e.g.

Therefore you should always use your vendor prefix in the naming of the extension, to ensure, that there are no naming conflicts with other plugins.

For the case you are describing there is a special ArrayStruct you can use to easier create an struct for an array. However the array struct expects that the input array is indexed by the key, so you may need to change the structure of your array data a bit:

$myExampleArray = [
    'foobar' => ['key' => 'foobar', 'val1' => 'bar', 'val2' => 'foobarfoo'],
    'barfoo' => ['key' => 'barfoo', 'val1' => 'foo', 'val2' => 'barfoobar']
];

$event->getResult()->addExtension('myExampleExtension', new ArrayStruct($myExampleArray);

If it is not that easy to change the structure of your array, your solution is totally fine too, but depending on the size of the array you might want to get rid of the extra loop through it.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x