Phoenix: роутер, контроллеры, HEEx и plugs
После урока вы сможете
- Читать и писать маршруты в Router
- Делать контроллер с действиями и changeset-потоком
- Понимать HEEx-шаблоны
- Собирать pipeline из Plug
Создание проекта
mix phx.new hello_web --binary-id
cd hello_web
mix deps.get
mix ecto.create
mix phx.server
Откройте http://localhost:4000.
Структура (упрощённо):
lib/hello_web/ # веб-слой
endpoint.ex
router.ex
controllers/
components/
lib/hello/ # домен (контексты)
priv/repo/migrations/
Router
defmodule HelloWeb.Router do
use HelloWeb, :router
pipeline :browser do
plug :accepts, ["html"]
plug :fetch_session
plug :fetch_live_flash
plug :put_root_layout, html: {HelloWeb.Layouts, :root}
plug :protect_from_forgery
plug :put_secure_browser_headers
end
pipeline :api do
plug :accepts, ["json"]
end
scope "/", HelloWeb do
pipe_through :browser
get "/", PageController, :home
resources "/posts", PostController
end
scope "/api", HelloWeb.Api do
pipe_through :api
get "/health", HealthController, :show
end
end
resources "/posts", PostController даёт REST-маршруты:
| Метод | Путь | Действие |
|---|---|---|
| GET | /posts | :index |
| GET | /posts/new | :new |
| POST | /posts | :create |
| GET | /posts/:id | :show |
| GET | /posts/:id/edit | :edit |
| PUT/PATCH | /posts/:id | :update |
| DELETE | /posts/:id | :delete |
Ограничение: resources "/posts", PostController, only: [:index, :show].
Имена путей: mix phx.routes, в коде — ~p"/posts/#{post}" (verified routes).
Controller
defmodule HelloWeb.PostController do
use HelloWeb, :controller
alias Hello.Content
alias Hello.Content.Post
def index(conn, _params) do
posts = Content.list_posts()
render(conn, :index, posts: posts)
end
def show(conn, %{"id" => id}) do
post = Content.get_post!(id)
render(conn, :show, post: post)
end
def new(conn, _params) do
changeset = Content.change_post(%Post{})
render(conn, :new, changeset: changeset)
end
def create(conn, %{"post" => post_params}) do
case Content.create_post(post_params) do
{:ok, post} ->
conn
|> put_flash(:info, "Пост создан")
|> redirect(to: ~p"/posts/#{post}")
{:error, %Ecto.Changeset{} = changeset} ->
render(conn, :new, changeset: changeset)
end
end
def edit(conn, %{"id" => id}) do
post = Content.get_post!(id)
changeset = Content.change_post(post)
render(conn, :edit, post: post, changeset: changeset)
end
def update(conn, %{"id" => id, "post" => post_params}) do
post = Content.get_post!(id)
case Content.update_post(post, post_params) do
{:ok, post} ->
conn
|> put_flash(:info, "Пост обновлён")
|> redirect(to: ~p"/posts/#{post}")
{:error, changeset} ->
render(conn, :edit, post: post, changeset: changeset)
end
end
def delete(conn, %{"id" => id}) do
post = Content.get_post!(id)
{:ok, _} = Content.delete_post(post)
conn
|> put_flash(:info, "Пост удалён")
|> redirect(to: ~p"/posts")
end
end
Контроллер тонкий: параметры → контекст → render / redirect / статус.
JSON API:
def show(conn, %{"id" => id}) do
post = Content.get_post!(id)
json(conn, %{id: post.id, title: post.title})
end
HEEx и компоненты (кратко)
HEEx — HTML + Elixir-вставки. В современных Phoenix — функции-компоненты:
# lib/hello_web/controllers/post_html/index.html.heex
<.header>
Посты
<:actions>
<.link navigate={~p"/posts/new"}>Новый пост</.link>
</:actions>
</.header>
<ul>
<%= for post <- @posts do %>
<li>
<.link navigate={~p"/posts/#{post}"}>{post.title}</.link>
</li>
<% end %>
</ul>
Форма с changeset:
<.simple_form :let={f} for={@changeset} action={~p"/posts"}>
<.input field={f[:title]} label="Заголовок" />
<.input field={f[:body]} type="textarea" label="Текст" />
<:actions>
<.button>Сохранить</.button>
</:actions>
</.simple_form>
@posts, @changeset — assigns, которые передали из render/3.
Layouts: root.html.heex оборачивает страницу; flash — через put_flash.
Plug pipeline
Каждый plug: (conn, opts) -> conn.
defmodule HelloWeb.Plugs.RequireUser do
import Plug.Conn
import Phoenix.Controller
def init(opts), do: opts
def call(conn, _opts) do
if conn.assigns[:current_user] do
conn
else
conn
|> put_flash(:error, "Войдите в аккаунт")
|> redirect(to: "/login")
|> halt()
end
end
end
В роутере:
pipeline :authenticated do
plug :browser
plug HelloWeb.Plugs.RequireUser
end
scope "/app", HelloWeb do
pipe_through :authenticated
get "/dashboard", DashboardController, :show
end
Встроенные plugs: парсинг тела, сессия, CSRF, логирование, статика — уже в Endpoint/Router.
Функциональный plug без модуля:
pipeline :browser do
plug :accepts, ["html"]
plug :fetch_session
# ...
end
Endpoint — входная дверь
HelloWeb.Endpoint — супервизорный процесс: сокеты, статика, парсеры, вызов Router.
Конфиг порта, URL, secret_key_base — в config/.
# truncate idea
plug Plug.Static, at: "/", from: :hello_web, gzip: false, only: HelloWeb.static_paths()
plug Plug.Session, @session_options
plug HelloWeb.Router
Генераторы
mix phx.gen.html Content Post posts title:string body:text user_id:references:users
mix phx.gen.json Accounts User users email:string name:string
mix phx.gen.context Content Comment comments body:text post_id:references:posts
Генератор создаёт миграцию, схему, контекст, контроллер, шаблоны и тесты — потом правьте под домен.
Ошибки и статусы
def show(conn, %{"id" => id}) do
case Content.fetch_post(id) do
{:ok, post} -> render(conn, :show, post: post)
:error -> conn |> put_status(:not_found) |> put_view(html: HelloWeb.ErrorHTML) |> render(:"404")
end
end
Или raise Ecto.NoResultsError из get! + fallback в ErrorHTML / ErrorJSON.
Мини-чеклист запроса
- Клиент → Endpoint (парсинг, сессия)
- Router выбирает pipeline + action
- Plugs обогащают
conn(assigns, halt) - Controller вызывает контекст
- HEEx рендерит HTML или
json/2отдаёт API
Чеклист: Phoenix основы
0 / 4 выполнено
Дочитали до конца?
Отметьте урок пройденным — так проще вернуться туда, где остановились.