In Magento 1, you could use the same Observer class with multiple methods and invoke those. As per the new structure, do we need to create a new Observer for every event handler or observer? Or is there a way to combine multiple event handlers in the same observer?


TL;DR: Yes, you need a class for every event you are observing.
Long version:
If you add all your observer methods in one single class then you end up with a class that knows too much and does too much. This violates the Single Responsibility Principle

Theoretically you could use the same observer for 2 events if the events are similar (they send the same data), but you should not do that.
You should keep your events separated.
This also makes it easier to rewrite and observer. You can just define a preference in di.xml for the class that observes a certain event.

  • Thanks. My events are certainly different. I am actually migrating an extension from 1.x to 2.1. The earlier version used to have just 1 Observer.php inside Model which was listening to all the events and executing business logic. Do you know a link or guide that can help with this migration? Also, didn't understand why would any changes be required in di.xml? – PhoenixGuru Mar 24 '17 at 9:09
  • I didn't say changes are required in di.xml. I said you could do that when/if needed. I don't have any links to help with the migration. But you can use this tutorial on how to create an observer in m2 webkul.com/blog/observers-in-magento2 – Marius Mar 24 '17 at 9:11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.