Phoenix Contexts Reference
Ash projects: Ash.Domain replaces Phoenix contexts for data access — use the ash-framework skill. Context boundary and PubSub patterns still apply.
Reference for designing and implementing Phoenix contexts (bounded contexts).
Iron Laws — Never Violate These
- CONTEXTS OWN THEIR DATA — Never query another context's schema directly via Repo
- SCOPES ARE MANDATORY (Phoenix 1.8+) — Every context function MUST accept scope as first parameter
- THIN CONTROLLERS/LIVEVIEWS — Controllers translate HTTP, business logic stays in contexts
- NO SIDE EFFECTS IN SCHEMAS — Use
Ecto.Multi for transactions with side effects
Context Structure
lib/my_app/
├── accounts/ # Context directory
│ ├── user.ex # Schema
│ ├── scope.ex # Scope struct (Phoenix 1.8+)
├── accounts.ex # Context module (public API)
Phoenix 1.8+ Scopes (CRITICAL)
All context functions MUST accept scope as first parameter:
def list_posts(%Scope{} = scope) do
from(p in Post, where: p.user_id == ^scope.user.id)
|> Repo.all()
end
def create_post(%Scope{} = scope, attrs) do
%Post{user_id: scope.user.id}
|> Post.changeset(attrs)
|> Repo.insert()
|> broadcast(scope, :created)
end
Quick Decisions
When to SPLIT contexts?
- Module exceeds ~400 lines
- Functions don't share domain language
- Could theoretically be a separate microservice
- Team member could own it independently
When to KEEP together?
- Resources share vocabulary and domain concepts
- Functions frequently operate on same data together
- Splitting would create excessive cross-context calls
Cross-Context References
# ✅ Reference by ID, convert at boundary
def create_order(%Scope{} = scope, user_id, product_ids) do
with {:ok, user} <- Accounts.fetch_user(scope, user_id) do
do_create_order(scope, user.id, product_ids)
end
end
# ❌ Reaching into other context's internals
alias MyApp.Accounts.User # Don't do this
Repo.all(from o in Order, join: u in User, ...) # Don't query other schemas
Anti-patterns
| Wrong |
Right |
Service objects (UserCreationService) |
Context functions (Accounts.create_user/2) |
| Repository pattern wrapping Repo |
Repo IS the repository |
| Direct Repo calls in controllers |
Delegate to context |
| Schema callbacks with side effects |
Use Ecto.Multi |
Version Notes
- Phoenix 1.8+: Uses built-in
%Scope{} struct for authorization context
- Phoenix 1.7: Requires manual authorization context (see
references/scopes-auth.md "Pre-Scopes Patterns")
References
For detailed patterns, see:
references/context-patterns.md - Full context module, PubSub, Multi, cross-boundary
references/scopes-auth.md - Scope struct, multi-tenant, authorization, plugs
references/routing-patterns.md - Verified routes, pipelines, API auth
references/plug-patterns.md - Function/module plugs, placement, guards
references/json-api-patterns.md - JSON controllers, FallbackController, API auth
1---2name: phoenix-contexts3description: Phoenix context design — creating/splitting contexts, Scope (1.8+), Ecto.Multi, PubSub, routers, plugs, controllers. Use when editing contexts, routers, or designing boundaries.4---5
6# Phoenix Contexts Reference
7
8> **Ash projects**: `Ash.Domain` replaces Phoenix contexts for data access — use the `ash-framework` skill. Context boundary and PubSub patterns still apply.
9
10Reference for designing and implementing Phoenix contexts (bounded contexts).
11
12## Iron Laws — Never Violate These
13
141. **CONTEXTS OWN THEIR DATA** — Never query another context's schema directly via Repo
152. **SCOPES ARE MANDATORY (Phoenix 1.8+)** — Every context function MUST accept scope as first parameter
163. **THIN CONTROLLERS/LIVEVIEWS** — Controllers translate HTTP, business logic stays in contexts
174. **NO SIDE EFFECTS IN SCHEMAS** — Use `Ecto.Multi` for transactions with side effects
18
19## Context Structure
20
21```
22lib/my_app/
23├── accounts/ # Context directory
24│ ├── user.ex # Schema
25│ ├── scope.ex # Scope struct (Phoenix 1.8+)
26├── accounts.ex # Context module (public API)
27```
28
29## Phoenix 1.8+ Scopes (CRITICAL)
30
31All context functions MUST accept scope as first parameter:
32
33```elixir
34def list_posts(%Scope{} = scope) do
35 from(p in Post, where: p.user_id == ^scope.user.id)
36 |> Repo.all()
37end
38
39def create_post(%Scope{} = scope, attrs) do
40 %Post{user_id: scope.user.id}
41 |> Post.changeset(attrs)
42 |> Repo.insert()
43 |> broadcast(scope, :created)
44end
45```
46
47## Quick Decisions
48
49### When to SPLIT contexts?
50
51- Module exceeds ~400 lines
52- Functions don't share domain language
53- Could theoretically be a separate microservice
54- Team member could own it independently
55
56### When to KEEP together?
57
58- Resources share vocabulary and domain concepts
59- Functions frequently operate on same data together
60- Splitting would create excessive cross-context calls
61
62### Cross-Context References
63
64```elixir
65# ✅ Reference by ID, convert at boundary
66def create_order(%Scope{} = scope, user_id, product_ids) do
67 with {:ok, user} <- Accounts.fetch_user(scope, user_id) do
68 do_create_order(scope, user.id, product_ids)
69 end
70end
71
72# ❌ Reaching into other context's internals
73alias MyApp.Accounts.User # Don't do this
74Repo.all(from o in Order, join: u in User, ...) # Don't query other schemas
75```
76
77## Anti-patterns
78
79| Wrong | Right |
80|-------|-------|
81| Service objects (`UserCreationService`) | Context functions (`Accounts.create_user/2`) |
82| Repository pattern wrapping Repo | Repo IS the repository |
83| Direct Repo calls in controllers | Delegate to context |
84| Schema callbacks with side effects | Use Ecto.Multi |
85
86## Version Notes
87
88- **Phoenix 1.8+**: Uses built-in `%Scope{}` struct for authorization context
89- **Phoenix 1.7**: Requires manual authorization context (see `references/scopes-auth.md` "Pre-Scopes Patterns")
90
91## References
92
93For detailed patterns, see:
94
95- `references/context-patterns.md` - Full context module, PubSub, Multi, cross-boundary
96- `references/scopes-auth.md` - Scope struct, multi-tenant, authorization, plugs
97- `references/routing-patterns.md` - Verified routes, pipelines, API auth
98- `references/plug-patterns.md` - Function/module plugs, placement, guards
99- `references/json-api-patterns.md` - JSON controllers, FallbackController, API auth