Shopware 6 - Tips, tricks and how to's

Preventing events from triggering again (and again, and again..)

Much of the stuff, that we need to do in Shopware 6, revolves around events. For example, if we need to do something, when the product detail page loads, we can create a subscriber like this:

Another useful kind of events are the ‘onWritten’ events, that get triggered, when something is written to an entity, let’s say when a product translation is updated:

This is of course great, but a problem can appear, when we want to write some additional data at this point. The thing, that will happen here is, that the event gets triggered again and our function is getting called again. And it writes the data again, so the event is triggered again and our function is caleed again. And again and again and so on, until the server ends up in error 500 in most cases.

This infinite loop is an unwanted recursion. Recursion is a situation, when a function calls itself. It is not necessarily a bad thing, it is a standard programming technique, that can be very useful. But it is also a bit dangerous, because it can lead to infinite loops. And what is the solution, when we find ourselves in an infinite loop? We jump out, of course! There are multiple ways to do it, but for me the most easy and elegant one, that I wanted to share with you today, is removing the subscriber from the dispatcher.

Dispatcher is a system class, that takes care of triggering events in Shopware 6. It knows about our subscribers and calls them, when the corresponding event happens. In the end, all we need to do, is to tell it, that after the first call of our subscriber, it should remove our subscriber from its list of subscribers for that event:

And that’s it – no more unwanted recursion in event subscribers!

UPDATE: this approach does not work in some cases, so I have come up with an alternative solution.