Based on my blog post
- What?
- How?
- Why?
- Elixir specific stuff
- Module naming
- OTP
- Show-and-tell example code
It is a pattern much similar to the Facade Pattern.
You probably already use it to some extend.
Diffs from Facade:
- Only isolates internal code
- Also isolates on file system level
- A Context covers a specific logical area of the application. A facade covers a specific technical area.
Pretty simple:
Refactoring existing code:
- Find a group of files that logically belong together
- Put them in the same dir and namespace
- Minimize public API by creating the context module
- Also minimize public types and structs
From scratch:
- After a few refactorings, it will become natural to isolate in contexts and benefits will be greater
- Profit
Immediate benefits of contexts:
- Smaller public API. Easier to call the code.
- Easier to understand a context as a logical chunk of the application.
- Easier to understand the entire codebase as a collection of contexts
Long term benefits:
- Explicit dependencies
- Explicit types and structs
- Forces developers to think about important stuff
- Easier to maintain and change the internal code or db structure.
- Easy to delete the entire context
Visualized:
VS
File structure
+ some_context
|-- some_context.ex
|-- some_thing.ex
Public/main module: MyApp.SomeContext
Inner module: MyApp.SomeContext.SomeThing
Since Elixir 1.5, simple add main module to supervisor:
children = [
SomeContext,
SomeOtherContext
]
Supervisor.start_link(children, strategy: :one_for_one)
And then implement a child_spec
in the main module:
def child_spec([]) do
%{
id: __MODULE__,
start: {SomeWorker, :start_link, []}
}
end
Or if starting a supervisor:
def child_spec([]) do
%{
id: __MODULE__,
start: {SomeSupervisor, :start_link, []},
type: :supervisor
}
end
Legolas.Geolocation
- Elixir 1.5 child spec docs: https://hexdocs.pm/elixir/Supervisor.html#module-child-specification
- Phoenix 1.3 release notes: http://phoenixframework.org/blog/phoenix-1-3-0-released
- My blog post on the topic: https://medium.com/@lasseebert/isolating-code-in-contexts-172ec93ce532
- Elixir forum post: https://elixirforum.com/t/how-would-you-explain-phoenix-contexts-to-a-newbie/5947/3