Search code examples
phpsymfonyeventsevent-dispatching

Is an Event Dispatcher the appropriate solution?


I'm working on a API project that needs to send emails and store statistics after (or before depending on the implementation) the response has been returned to the client. For both cases I'm considering the Symfony's EventDispatcher component (I'm not using Symfony as the framework) so each controller action will dispatch an event to add an email to the queue or insert the data into the statistics database table.

So the thing would look something like this

Controller 
    => Send Response to client
    => Dispatch Event email => EmailEventListener => Mail queue
    => Dispatch Event stats => StatsEventLister => Database 

I'm considering this because I want this internal actions to be as asynchronous as they could be. Is this appropriate solution for this case?

EDIT: As Jovan Perovic suggested I'm adding more information. The API is a REST API that users communicate with it via web or mobile apps and I want to log, store stats and send notifications (emails primarily) without penalizing the performance of the API, the first idea was to use something that run after returning the response to the client but I don't know if that's possible using the EventDispatcher. Even if a use queue to process stats or notifications I need a centralized place where all the controllers can send information so logs be written and stats stored.

I hope my goal is now more clear. Sorry.


Solution

  • I think you could use Request filters (After would be suitable for you), although, I have never attempted to use them outside of Symfony2 framework.

    As for async operations, in general, sockets are your friend. You could externalize the logic, by sending data to some socket which will in turn process the data accordingly. If that processing is non-essential (e.g. email and stats), your request could be finished even if your external mechanism fails.

    I read some time ago about Gearman here (just an example) which might help up externalize that by creating a separate jobs.

    Hope this sheds some light here :)