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?
Advertisement
Answer
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.