Skip to content

Instantly share code, notes, and snippets.

@jeffkreeftmeijer
Created January 13, 2019 13:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jeffkreeftmeijer/5fee562869ad20fbdfaeed02a758f285 to your computer and use it in GitHub Desktop.
Save jeffkreeftmeijer/5fee562869ad20fbdfaeed02a758f285 to your computer and use it in GitHub Desktop.

Contexts in Phoenix

In Phoenix, contexts provide the interface to your data layer. They are used to read and write data to your database, but the context model can also be used to talk to external APIs or resources that don’t come from a database.

Contexts, schemas and repositories

In a datbase-backed application, schemas describe the resources in your database. For a blog, your might have an Article schema to store the articles, and a Comment schema to store comments users post to your articles. Your schemas are used to model the data for both of these, encoding them to be stored in the database, decoding data from the database, and validating data to make sure it’s fit to be stored.

A context is tasked with communicating with the repository. Our blog can have a Publications context to handle dealing with articles and their comments. To create a new article, the context knows to create a new Article struct, and use the Article.changeset/2 function to convert the passed attributes to an article, which is can then pass to the repo via Repo.insert/1.

To add a new comment to an article, it knows how to find the correct article, create a comment, and add it. It might also increase a comment counter which is cached on the article row in the database, for example.

Contexts and schema’s versus Models

Coming from a traditional MVC framework like Ruby on Rails, contexts may seem like an extra layer to worry about. Other frameworks use a model layer, which essentially does the work of a schema and a context by handling both validations and database commnunication.

This makes database communication, which is an implementation detail, leak into the rest of the codebase. To add a comment to an article, the controller now needs to find the article to add the comment.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment