What is Mediator — design pattern?
Mediator is a very useful design pattern, which fully use the SOLID principle, so avoiding dependencies between classes. In practice we create one class, which will be an interface for all elements of the project and we pass only commands to this interface and this interface handles the transfer.
The Mediator Pattern dates to 1994 in the popular book “Design Patterns: Elements of Reusable Object-Oriented Software”. In a nutshell, the most common definitione is (I’ve borrowed it from Wikipedia),
The essence of the Mediator Pattern is to “define an object that encapsulates how a set of objects interact”. It promotes loose coupling by keeping objects from referring to each other explicitly, and it allows their interaction to be varied independently. Client classes can use the mediator to send messages to other clients, and can receive messages from other clients via an event on the mediator class.
Below you can find the graphical description of Mediator design pattern idea:
Mediator in GrandNode
We always try to use only the most modern technologies to provide technological advanced solution. That’s why we’ve rewritten whole project to use only asynchronous methods. We’ve decided also to bet on Mediator, because we are convinced that it will ease up the many processes in our e-commerce platform and save resources when manage advanced operations.
We will create a simple plugin, which will make something after order placement. In the example, it will insert a short, information text to System Log. But it’s a great start for creating a simple integration between ERP system and e-commerce application.
In the created example we will make a plugin which will use the Order Placed Event. So we should inherit from BasePlugin, as every GrandNode plugin inherits from it and from INotificationHandler<OrderPlacedEvent>.
We will use the default logger, available out of the box in GrandNode.
Here is the core of the plugin, which was mentioned above:
It can be also a great skeleton for plugin, which will send a SMS notification to store owner when order will be placed. Below you can find another great example of Mediator usage in GrandNode, we will use Subscribed Email Event, which can be used to integrate your store with MailChimp or any kind of email marketing tools.
Last example can be combined also with Discount newsletter plugin, after activation you will be able to send welcome email with discount, for your new subscribers.