I’m learning about Channels now and I’m seeing a lot of tutorials/documentation broadcasting from Channels even though I see a little bit of references to broadcasting from a Controller. I stumbled across https://github.com/Angarsk8/Loopa-News/blob/master/web/controllers/api/post_controller.ex and noticed the broadcast is referenced from the Controller. Instinctively I would look for updates from a Controller so this makes sense to me. However, I don’t know how I’d feel about it over time.
Can anyone talk through the Pros and Cons of broadcasting from a Controller vs a Channel?
I stumbled across https://github.com/Angarsk8/Loopa-News/blob/master/web/controllers/api/post_controller.ex and noticed the broadcast is referenced from the Controller.
I assume this particular example is not the best resource of how to write controller. It uses standard MVC concepts from pre Phoenix 1.3, where Repo is accessed from controller immediately rather than through separate module that provides access to data and hides Repo. Please take a look at Phoenix Contexts it describes better the idea.
Having said that, I think Broadcaster should be another module in your app that wraps and hides how it broadcasts events. Another way I think of controller action is - it should look lightweight, accept implicit request as an input and return with response, everything else should be hidden under “context modules of business logic”.
I appreciate the response. Yes, I’m familiar with Contexts and how they are used in Phoenix.
Are you suggesting that the broadcast should be moved into a Context? From my understanding, Context files (for example:
accounts.ex) are responsible for the domain logic AND interacting with external dependancies like the DB (
Repo) and making calls outside the applications (http requests), etc… however, a broadcast via websockets can act as both a response to the initial request, and an external message sent to all parties interested… so I’m still unclear.
A great place for a response is the Controller. A “logical” place to broadcast from would be a Channel.