路由、控制器与 Plugs
定义路由、实现控制器操作,并使用 Plugs 构建模块化且可复用的请求处理流水线。
路由、控制器与 Plugs 是 CoddyKit 上的免费 Elixir & Phoenix: Scalable Backend Development 课时。 这是第 2 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Elixir & Phoenix: Scalable Backend Development 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Elixir & Phoenix: Scalable Backend Development 课程共包含 4 节课。
本课时的部分内容尚未翻译,以英文显示。
Mapping Your Web Requests
Welcome to routing in Phoenix! Think of routing as your application's traffic controller. When a user visits a URL, the router determines which part of your code should handle that request.
It's how Phoenix connects an incoming web address (like /users) to a specific function in your application.
The `router.ex` File
In Phoenix, all your routes are defined in the lib/my_app_web/router.ex file. This file uses special macros to declare how different HTTP methods (GET, POST, PUT, DELETE) map to your application's logic.
You'll often see routes grouped into scopes and processed by pipelines, which apply common behaviors.
Defining a Simple Route
Let's look at how a basic route is defined. Here, a GET request to the root path / is mapped to the index function within PageController.
Notice the pipe_through :browser which applies a set of common behaviors to browser requests.
defmodule MyPhoenixAppWeb.Router do
use MyPhoenixAppWeb, :router
pipeline :browser do
plug :accepts, ["html"]
# ... other plugs for sessions, security, etc.
end
scope "/", MyPhoenixAppWeb do
pipe_through :browser
# Maps GET / to MyPhoenixAppWeb.PageController.index
get "/", PageController, :index
# Maps GET /hello to MyPhoenixAppWeb.PageController.hello
get "/hello", PageController, :hello
end
endControllers: Handling Requests
Once the router directs a request, a controller takes over. Controllers are Elixir modules that contain actions (functions) responsible for handling specific requests.
Their main job is to:
- Receive request parameters.
- Perform necessary business logic (e.g., fetch data).
- Prepare a response, often by rendering a template.
Your First Controller Action
Controller actions are just functions that accept two arguments: conn (the connection struct) and params (request parameters).
Here's a simple PageController with an index action that renders an index.html template.
defmodule MyPhoenixAppWeb.PageController do
use MyPhoenixAppWeb, :controller
# This action handles requests for the root path "/"
def index(conn, _params) do
# The render function looks for a template like page/index.html.heex
render(conn, "index.html")
end
# This action handles requests for "/hello"
def hello(conn, _params) do
text(conn, "Hello from Phoenix!")
end
endPath Helpers: Generating URLs
Instead of hardcoding URLs in your templates or code, Phoenix provides path helpers. These are functions that generate URLs based on your defined routes.
Using path helpers makes your links robust. If you change a route's path, you only update it in router.ex, and all generated links will automatically update.
For example, ~p"/" generates the root path.
Plugs: Request Middleware
Plugs are composable functions or modules that process the Plug.Conn (connection) struct. They act like middleware, allowing you to intercept and modify requests before they reach a controller, or modify responses after they leave.
Think of them as a series of steps a request goes through. Each plug can transform the request (or halt it) and pass it to the next plug in the pipeline.
Creating a Custom Plug
Plugs are simple Elixir modules implementing the init/1 and call/2 functions. init/1 is for configuration, and call/2 does the actual work.
Here's a plug that logs the request path and adds a custom header to the response:
defmodule MyPhoenixAppWeb.Plugs.MyLogger do
import Plug.Conn
def init(opts), do: opts
def call(conn, _opts) do
IO.puts("Request received for path: #{conn.request_path}")
put_resp_header(conn, "X-Custom-Header", "Hello from Plug!")
end
endUsing a Custom Plug
To use your custom plug, you add it to a pipeline in your router.ex file. All requests passing through that pipeline will then be processed by your plug.
For example, adding plug MyPhoenixAppWeb.Plugs.MyLogger to the :browser pipeline means every browser request will trigger this plug.
- Plug.Parsers: Parses request bodies (JSON, forms).
- Plug.Logger: Logs request details.
- Plug.Static: Serves static assets like CSS/JS.
Quick Check: Phoenix Request Flow
Let's test your understanding of how Phoenix handles web requests.
Recap: Routing, Controllers, Plugs
In this lesson, you've learned the core components that handle web requests in Phoenix:
- Routes (in
router.ex) map incoming URLs to controller actions. - Controllers contain actions (functions) that execute business logic and prepare responses.
- Plugs are reusable components that process the request connection (
Plug.Conn) in a pipeline, before or after the controller.
Together, these form a powerful and flexible system for building web applications.
用 AI 导师学习 Elixir — 免费
在浏览器中编写并运行真实代码,获得全天候 AI 导师的即时帮助,并在网页或应用中继续学习。
- 课程
- 12
- 课程
- 48
常见问题解答
「路由、控制器与 Plugs」课时是免费的吗?
是的 — 「路由、控制器与 Plugs」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Elixir & Phoenix: Scalable Backend Development 课程的其余内容,请升级到 CoddyKit PRO。 Elixir & Phoenix: Scalable Backend Development 课程共包含 4 节课。
「路由、控制器与 Plugs」这节课中我会学到什么?
定义路由、实现控制器操作,并使用 Plugs 构建模块化且可复用的请求处理流水线。 你通过在浏览器中直接运行的动手代码来练习 Elixir & Phoenix: Scalable Backend Development,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 Elixir & Phoenix: Scalable Backend Development 需要有经验吗?
无需任何先前经验。CoddyKit 上的 Elixir & Phoenix: Scalable Backend Development 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 2 节课,共 4 节。
「路由、控制器与 Plugs」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 Elixir & Phoenix: Scalable Backend Development 课中编写并运行代码吗?
能。每节 Elixir & Phoenix: Scalable Backend Development 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。