Catalog / Phoenix Framework Cheatsheet

Phoenix Framework Cheatsheet

A comprehensive cheat sheet covering essential Phoenix framework commands, directory structure, routing, Ecto interactions, and more, with examples.

Getting Started

Installation

Ensure you have Erlang, Elixir, Node.js, and PostgreSQL installed.

# Install Phoenix
mix local.hex
mix archive.install https://github.com/phoenixframework/archives/raw/master/phx_new.ez

Project Creation

Create a new Phoenix project:

mix phx.new hello
cd hello
mix ecto.create
mix phx.server

This generates a basic Phoenix application. Follow the instructions to set up the database and start the server.

Directory Structure

Key Directories

_build/

Compiled Elixir code.

assets/

CSS, JavaScript, and static files.

config/

Application configuration files.

deps/

Project dependencies.

lib/

Source code for the application, including contexts, schemas, and web-related files.

priv/

Database migrations and static assets.

test/

Tests for the application.

Routing

Basic Routing

Define routes in lib/hello_web/router.ex.

get "/", PageController, :index

Resource Routing

Generate routes for a resource:

resources "/users", UserController do
  resources "/posts", PostController
end

Path Helpers

Use path helpers to generate URLs:

user_post_path(conn, :index, 17)     # → /users/17/posts
user_post_path(conn, :show, 17, 12)  # → /users/17/posts/12

Controllers and Conn

Accessing Request Data

Access request data through the conn:

conn.host          # → "example.com"
conn.method        # → "GET"
conn.path_info     # → ["posts", "1"]
conn.request_path  # → "/posts/1"

Modifying the Conn

Use conn functions to modify the response:

conn
|> put_status(202)
|> html("<html><head>···")
|> json(%{ message: "Hello" })
|> text("Hello")
|> redirect(to: "/foo")
|> render("index.html")
|> render("index.html", hello: "world")
|> render(MyApp.ErrorView, "404.html")

Ecto Migrations

Generating Migrations

Generate a migration file:

mix ecto.gen.migration update_posts_table

Migration Example

Example migration:

def change do
  create table(:documents) do
    add :title, :string
    add :title, :string, default: "Hello"
    add :body, :text
    add :age, :integer
    add :price, :float, precision: 10, scale: 2
    timestamps()
  end
end

Generating HTML

Generating HTML Resources

Generate HTML resources using phx.gen.html:

mix phx.gen.html \
    Accounts \
    Profile \
    profiles \
    email:string \
    age:integer

Replace Accounts, Profile, profiles, email, age with your domain, schema, table name, and attributes respectively.