Phoenix Contexts Reference
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
${CLAUDE_SKILL_DIR}/references/scopes-auth.md "Pre-Scopes Patterns")
References
For detailed patterns, see:
${CLAUDE_SKILL_DIR}/references/context-patterns.md - Full context module, PubSub, Multi, cross-boundary
${CLAUDE_SKILL_DIR}/references/scopes-auth.md - Scope struct, multi-tenant, authorization, plugs
${CLAUDE_SKILL_DIR}/references/routing-patterns.md - Verified routes, pipelines, API auth
${CLAUDE_SKILL_DIR}/references/plug-patterns.md - Function/module plugs, placement, guards
${CLAUDE_SKILL_DIR}/references/json-api-patterns.md - JSON controllers, FallbackController, API auth
Converted and distributed by TomeVault — claim your Tome and manage your conversions.
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. Use when this capability is needed.4---56# Phoenix Contexts Reference78Reference for designing and implementing Phoenix contexts (bounded contexts).910## Iron Laws — Never Violate These11121. **CONTEXTS OWN THEIR DATA** — Never query another context's schema directly via Repo132. **SCOPES ARE MANDATORY (Phoenix 1.8+)** — Every context function MUST accept scope as first parameter143. **THIN CONTROLLERS/LIVEVIEWS** — Controllers translate HTTP, business logic stays in contexts154. **NO SIDE EFFECTS IN SCHEMAS** — Use `Ecto.Multi` for transactions with side effects1617## Context Structure1819```20lib/my_app/21├── accounts/ # Context directory22│ ├── user.ex # Schema23│ ├── scope.ex # Scope struct (Phoenix 1.8+)24├── accounts.ex # Context module (public API)25```2627## Phoenix 1.8+ Scopes (CRITICAL)2829All context functions MUST accept scope as first parameter:3031```elixir32def list_posts(%Scope{} = scope) do33 from(p in Post, where: p.user_id == ^scope.user.id)34 |> Repo.all()35end3637def create_post(%Scope{} = scope, attrs) do38 %Post{user_id: scope.user.id}39 |> Post.changeset(attrs)40 |> Repo.insert()41 |> broadcast(scope, :created)42end43```4445## Quick Decisions4647### When to SPLIT contexts?4849- Module exceeds ~400 lines50- Functions don't share domain language51- Could theoretically be a separate microservice52- Team member could own it independently5354### When to KEEP together?5556- Resources share vocabulary and domain concepts57- Functions frequently operate on same data together58- Splitting would create excessive cross-context calls5960### Cross-Context References6162```elixir63# ✅ Reference by ID, convert at boundary64def create_order(%Scope{} = scope, user_id, product_ids) do65 with {:ok, user} <- Accounts.fetch_user(scope, user_id) do66 do_create_order(scope, user.id, product_ids)67 end68end6970# ❌ Reaching into other context's internals71alias MyApp.Accounts.User # Don't do this72Repo.all(from o in Order, join: u in User, ...) # Don't query other schemas73```7475## Anti-patterns7677| Wrong | Right |78|-------|-------|79| Service objects (`UserCreationService`) | Context functions (`Accounts.create_user/2`) |80| Repository pattern wrapping Repo | Repo IS the repository |81| Direct Repo calls in controllers | Delegate to context |82| Schema callbacks with side effects | Use Ecto.Multi |8384## Version Notes8586- **Phoenix 1.8+**: Uses built-in `%Scope{}` struct for authorization context87- **Phoenix 1.7**: Requires manual authorization context (see `${CLAUDE_SKILL_DIR}/references/scopes-auth.md` "Pre-Scopes Patterns")8889## References9091For detailed patterns, see:9293- `${CLAUDE_SKILL_DIR}/references/context-patterns.md` - Full context module, PubSub, Multi, cross-boundary94- `${CLAUDE_SKILL_DIR}/references/scopes-auth.md` - Scope struct, multi-tenant, authorization, plugs95- `${CLAUDE_SKILL_DIR}/references/routing-patterns.md` - Verified routes, pipelines, API auth96- `${CLAUDE_SKILL_DIR}/references/plug-patterns.md` - Function/module plugs, placement, guards97- `${CLAUDE_SKILL_DIR}/references/json-api-patterns.md` - JSON controllers, FallbackController, API auth9899---100> Converted and distributed by [TomeVault](https://tomevault.io/claim/oliver-kriska) — claim your Tome and manage your conversions.101<!-- tomevault:4.0:skill_md:2026-04-11 -->