File that holds the context that makes the business logic

Whenever we create a new project using mix phx.new hello, there is a generated file called hello.ex that says it holds the contexts that makes the business logic. Something like that. It is under /lib together with hello_web.ex.

What is the purpose of it. What kind of logics should be in there?

I think that comments a bit of a misnomer, at least where it’s placed.

A context is really just an elixir module. The guide has a section on contexts.

You have “contexts” in lib/<my_app> (possibly they’re considered contexts in lib/<my_app_web> too). At it’s most basic you have a context for each of your db tables and your CRUD logic goes in those contexts.

Where that comment is written could also be considered a context, where you might write some code that effects your entire application. I’m not sure off the top of my head what I’d put in there. Maybe some helper functions but I’d be more likely to put helpers in their own “helper” module.

The whole thing is more of a guideline than a rule, but generally the idea is keep related code in the same context (all the code that operates on a user, all the code that operates on authentication – may not have a corresponding db table, etc).

3 Likes