0Pricing
Elixir & Phoenix: Scalable Backend Development · Ders

Yönlendirme, Denetleyiciler ve Eklentiler

Modüler ve yeniden kullanılabilir istek boru hatları oluşturmak için yollar tanımlayın, denetleyici eylemlerini uygulayın ve Plugs kullanın.

Yönlendirme, Denetleyiciler ve Eklentiler, CoddyKit'te ücretsiz bir Elixir & Phoenix: Scalable Backend Development dersidir. Bu, 4 dersinin 2. dersidir. Aşağıdan dersin tamamını ücretsiz okuyabilir, sonra tarayıcıda yerleşik kod editörü ve 7/24 yapay zeka koçu ile uygulamalı olarak pratik yapabilirsin. Bu, Elixir & Phoenix: Scalable Backend Development öğrenme yolunun bir parçasıdır ve ilerlemeniz web ve CoddyKit uygulaması arasında senkronize olur. Elixir & Phoenix: Scalable Backend Development kursu toplamda 4 dersten oluşur.

Bu dersin bazı bölümleri henüz çevrilmemiş olup İngilizce olarak gösterilmektedir.

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
end

Controllers: 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
end

Path 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
end

Using 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.

Sıkça Sorulan Sorular

“Yönlendirme, Denetleyiciler ve Eklentiler” dersi ücretsiz mi?

Evet — “Yönlendirme, Denetleyiciler ve Eklentiler” dersin tüm metni burada web'de ücretsiz olarak okunabilir. Etkileşimli olarak pratik yapmak (yerleşik kod editörü ve 7/24 yapay zeka koçu) ve Elixir & Phoenix: Scalable Backend Development kursunun geri kalanını açmak için CoddyKit PRO'ya yükselt. Elixir & Phoenix: Scalable Backend Development kursu toplamda 4 dersten oluşur.

“Yönlendirme, Denetleyiciler ve Eklentiler” dersinde ne öğreneceğim?

Modüler ve yeniden kullanılabilir istek boru hatları oluşturmak için yollar tanımlayın, denetleyici eylemlerini uygulayın ve Plugs kullanın. Elixir & Phoenix: Scalable Backend Development ile uygulamalı kodu tarayıcıda doğrudan çalıştırarak pratik yaparsın ve 7/24 yapay zeka koçu dersi çalışırken sorularını yanıtlar.

Elixir & Phoenix: Scalable Backend Development öğrenmeye başlamak için deneyim gerekli mi?

Önceden deneyim gerekmez. CoddyKit'te Elixir & Phoenix: Scalable Backend Development, başlangıçtan ileri seviyeye kadar yapılandırıldığı için buradan başlayabilir veya başından başlayıp kendi hızında ilerleme yapabilirsin. Bu, 4 dersinin 2. dersidir.

“Yönlendirme, Denetleyiciler ve Eklentiler” dersi ne kadar sürer?

Çoğu CoddyKit dersi yaklaşık 5–10 dakika sürer. Her biri kısa ve etkileşimli olduğu için sabit ilerleme yaparsın ve web ile uygulama arasında tam olarak bıraktığın yerden devam edebilirsin.

Bu Elixir & Phoenix: Scalable Backend Development dersinde kod yazıp çalıştırabilir miyim?

Evet. Her Elixir & Phoenix: Scalable Backend Development dersi yerleşik bir kod editörü içerir, bu sayede tarayıcıda gerçek kod yazıp çalıştırabilir ve anlık yapay zeka geri bildirimi alırsın — yerel kurulum gerekli değildir.

Bu kursun tüm dersleri

  1. Phoenix Projesi Kurulumu ve Yapısı
  2. Yönlendirme, Denetleyiciler ve Eklentiler
  3. Görünümler, Şablonlar ve LiveView Temelleri
  4. Phoenix Channels ile Gerçek Zamanlı Özellikler
← Elixir & Phoenix: Scalable Backend Development Sayfasına Dön