Phoenix 1.3 introduced the idea of contexts to the Elixir community. The Phoenix team was inspired by “bounded contexts” as described by Eric Evans in his book Domain-Driven Design. This pattern suggested a new way of structuring applications, and the team updated Phoenix’s generators so that contexts became the default behavior.

What is a context?

With contexts, we can group related functionality. A context consists of a single main module (referred to as the context module) and optionally a directory with more modules that help implement the functionality of the context. A context may have many modules or one, but in either case, the context module contains the external interface of the context.

This is not a new pattern, and it’s not unique to Phoenix applications. The Ecto library itself uses contexts. For example, the Ecto.Query module is the external interface for building and manipulating queries. Several other internal modules are under the same namespace (Ecto.Query.Builder, Ecto.Query.Planner, and others), but we don’t work with those modules directly. The Ecto.Query module contains the API that we call, and the other modules provide support by making that API work.

Get hands-on with 1200+ tech skills courses.