lundi 18 avril 2016

Best practice to use interface for different event handling

I have a common method i.e. onMessage that takes input from different clients ( Websocket client ).

Clients send different messages in a specific data format i.e.

{
    "event" : "init",
    "data" : {}
}

All this different messages are parsed by onMessage function.

Now i have a use case where based on event of message for e.g. if event is init publish something, if event is heartbeat publish something etc.

What's the most generic way so that event with different implementation can be added even later.

So far i have an idea that i have to use interfaces. What i'm doing is is i have a Interface called EventInterface with publish, getName method.

Then i created a class called Init that implements EventInterface and defines publish & getName method.

Now how do i connect my onMessage function with this different Event classes. This are type of different Event-listeners i believe.

Right now one solution that comes in my mind is to create class called Events that stores all the event Object i.e. Init class object, HeartBeat class object in an array.

So when i create object from Events and pass the message from onMessage method and call magic method it loops through event object array and matches name using getName method of the appropriate event classes and calls publish methods.

Idk if this is the best way to handle this use case. If this is okay way then is there anyway i can avoid manually adding objects to event object method of Events class? Or that's okay?

Aucun commentaire:

Enregistrer un commentaire