Phoenix
01 / 02

Phoenix Fundamentals: Router, Controllers & Contexts

Phoenix: Router, Controllers & Contexts

Phoenix is a productive, high-performance web framework for Elixir, running on the Erlang VM (BEAM) -- inheriting its lightweight process model, fault tolerance, and strong support for massive concurrency.

Router & Controller

# router.ex
scope "/api", MyAppWeb do
  pipe_through :api
  resources "/users", UserController, only: [:index, :show, :create]
end

# user_controller.ex
def create(conn, %{"user" => user_params}) do
  case Accounts.create_user(user_params) do
    {:ok, user} -> json(conn, user)
    {:error, changeset} -> conn |> put_status(422) |> json(changeset)
  end
end

Contexts: Grouping Business Logic

defmodule MyApp.Accounts do
  def create_user(attrs) do
    %User{}
    |> User.changeset(attrs)
    |> Repo.insert()
  end
end

# Contexts (Accounts, Blog) group related logic behind a
# clean module API -- controllers don't need to know HOW
# Accounts.create_user actually works internally

Ecto Changesets

def changeset(user, attrs) do
  user
  |> cast(attrs, [:name, :email])
  |> validate_required([:name, :email])
  |> validate_format(:email, ~r/@/)
end

# Validates and casts incoming data before persistence,
# tracking what changed and any validation errors

Pipelines

A router pipeline (like pipeline :api do plug :accepts, ["json"] end) groups shared plugs applied to all routes using it -- avoiding repeating common processing logic (like requiring auth) across many individual routes.

Keep your own version of these notes — editable, searchable, and organised by your stack.

Start free