Phoenix

Configuration

Macros, Macros everywhere. One of the most useful one is config (config/2 with environment and opts, and config/3 with environment, key, and opts). It is present in proj_root/config/*.exs.

config :namespace, key_to_be_configured,
  key: value,
  key: value,
  key: value

Refer to Config for documentation. For example

config :learning, App.Repo,
  username: "postgres",
  password: "postgres",
  hostname: "localhost",
  database: "app_dev",
  pool_size: 10

This will set config for App.Repo and assuming Ecto.Repo is used to define the repo, it will use adapter Ecto.Adapters.Postgres (by default) and use config values to connect to the database.

Constructor Reducers and Converter in Phoenix

Plug.Conn is useful struct used heavily in Phoenix. It is a struct that holds information about the connection. It is passed around in the pipeline and is used to render the response. It is defined in Plug.Conn module. Plug has many Reducer functions to modify the connection. Pheonix is giant function with CRC pipeline.

connection_from_request
|> endpoint
|> router
|> custom_application

LiveView

It is closer to react. Router routes to the liveview and then it is mounted and rendered. Events are observed and re-rendered. mount/3 -> render/1 -> handle_event/3 Pheonix LiveView is a set of three main components:

  • Phoenix.Component

  • Phoenix.LiveView

  • Phoenix.LiveComponent

How?

  • You use a live/3 function in the router to route to a liveview.

scope "/", NameWeb do
pipe_through :browser

get "/", PageController, :home
live "/live", NameLive
end
  • Assign a socket to the liveview

def mount(_params, _session, socket) do
{:ok, assign(socket, :message, "Hello World")}
end

Mount either returns {:ok, socket} or {:error, reason}.

  • Render the liveview

def render(assigns) do
    ~H"""
        Hello <%= @message %>
    """
end

~H is a sigil for HEEx.

  • Handle events

def handle_event("click", %{"message" => message}, socket) do
{:noreply, assign(socket, :message, "Clicked!")}
end

Same as render it will return {:noreply, socket} or {:reply, {:ok, assigns}, socket} or {:stop, reason, socket}.

Generators

phx.gen provides a bunch of generator functions to generate boilerplate code.

  • phx.gen.auth Accounts User users where Accounts is the context, User is the schema, and users is the plural name(bu default also table name). Authentication Service is defined in app/lib/app_web/user_auth.ex. Almost everything in here is a Plug.

Backlinks