Peace of mind from prototype to production - comprehensive web framework for Elixir
Phoenix provides comprehensive code generation through Mix tasks that create boilerplate code, database migrations, and complete CRUD interfaces. The generators follow Phoenix conventions and integrate with Ecto for database operations.
Phoenix includes generators for all major application components, from basic schemas to complete authentication systems.
# Mix Task: mix phx.gen.auth Context Schema table [fields] [options]
# Generates complete authentication system including:
# - User schema with password hashing
# - UserToken schema for session/reset tokens
# - Context with authentication functions
# - Controllers for registration, login, settings
# - Templates and views for all auth pages
# - Database migrations and tests# Complete authentication system
mix phx.gen.auth Accounts User users name:string email:string:unique
# Custom confirmation field
mix phx.gen.auth Accounts User users email:string:unique \
--confirm-email --live
# With custom table name
mix phx.gen.auth Accounts User accounts email:string:unique# Mix Task: mix phx.gen.context Context Schema table [fields]
# Generates context module with schema, database functions, and tests
# Mix Task: mix phx.gen.schema Context.Schema table [fields]
# Generates schema module only with changeset functions
# Mix Task: mix phx.gen.embedded Schema [fields]
# Generates embedded schema (no database table)
# Supported field types:
# :string, :text, :integer, :float, :decimal, :boolean
# :date, :time, :naive_datetime, :utc_datetime
# :uuid, :binary, :array, :map, :enum# Blog context with posts and comments
mix phx.gen.context Blog Post posts title:string body:text published:boolean
mix phx.gen.context Blog Comment comments post_id:references:posts \
author:string body:text
# E-commerce product catalog
mix phx.gen.context Catalog Product products \
name:string description:text price:decimal:precision:10:scale:2 \
sku:string:unique category:enum:electronics:books:clothing
# User profile with embedded address
mix phx.gen.context Accounts Profile profiles \
user_id:references:users bio:text avatar_url:string
mix phx.gen.embedded Address street:string city:string state:string zip:string# Mix Task: mix phx.gen.html Context Schema table [fields] [options]
# Generates full CRUD HTML interface with controller, views, templates
# Mix Task: mix phx.gen.json Context Schema table [fields] [options]
# Generates JSON API interface with controller and JSON views
# Mix Task: mix phx.gen.live Context Schema table [fields] [options]
# Generates LiveView interface with real-time updates
# Common options:
# --no-context # Skip generating context
# --no-schema # Skip generating schema
# --web Module # Specify web module namespace
# --context-app # Generate context in different app# Complete HTML CRUD for blog posts
mix phx.gen.html Blog Post posts title:string body:text \
published:boolean published_at:naive_datetime
# JSON API for mobile app
mix phx.gen.json Accounts User users name:string email:string \
--no-context
# Real-time LiveView interface
mix phx.gen.live Catalog Product products name:string price:decimal \
description:text in_stock:boolean
# Admin interface in separate namespace
mix phx.gen.html Blog Post posts title:string body:text \
--web AdminPhoenix provides specialized generators for real-time features and communication.
# Mix Task: mix phx.gen.channel Channel [options]
# Generates:
# - Channel module with join/handle_in callbacks
# - Channel test file
# - Socket configuration (if needed)# Chat room channel
mix phx.gen.channel Room
# User notification channel
mix phx.gen.channel User
# Game lobby channel
mix phx.gen.channel GameLobby# lib/my_app_web/channels/room_channel.ex
defmodule MyAppWeb.RoomChannel do
use Phoenix.Channel
@impl true
def join("room:lobby", payload, socket) do
if authorized?(payload) do
{:ok, socket}
else
{:error, %{reason: "unauthorized"}}
end
end
# Channels can be used in a request/response fashion
# by sending replies to requests from the client
@impl true
def handle_in("ping", payload, socket) do
{:reply, {:ok, payload}, socket}
end
# It is also common to receive messages from the client and
# broadcast to everyone in the current topic (room:lobby).
@impl true
def handle_in("shout", payload, socket) do
broadcast(socket, "shout", payload)
{:noreply, socket}
end
# Add authorization logic here as required.
defp authorized?(_payload) do
true
end
end# Mix Task: mix phx.gen.socket Socket [options]
# Generates:
# - Socket module with connect/id callbacks
# - Endpoint socket configuration# User socket for authenticated connections
mix phx.gen.socket User
# Admin socket for management interface
mix phx.gen.socket Admin
# API socket for service-to-service communication
mix phx.gen.socket Api# Mix Task: mix phx.gen.presence [Module] [options]
# Generates:
# - Presence module with tracking callbacks
# - Integration with PubSub system# User presence tracking
mix phx.gen.presence UserPresence
# Game room presence
mix phx.gen.presence GamePresencedefmodule MyApp.UserPresence do
@moduledoc """
Provides presence tracking to channels and processes.
See the [`Phoenix.Presence`](http://hexdocs.pm/phoenix/Phoenix.Presence.html)
docs for more details.
"""
use Phoenix.Presence, otp_app: :my_app,
pubsub_server: MyApp.PubSub
end# Mix Task: mix phx.gen.notifier Context Notifier [functions]
# Generates:
# - Notifier module with email/SMS functions
# - Templates for notifications
# - Tests for delivery functions# User account notifications
mix phx.gen.notifier Accounts UserNotifier \
welcome_email reset_password_email account_locked_email
# Order notifications for e-commerce
mix phx.gen.notifier Orders OrderNotifier \
order_confirmed_email order_shipped_email order_delivered_emailPhoenix provides various utilities for development, debugging, and deployment preparation.
# Mix Task: mix phx.server
# Start development server with live code reloading
# Mix Task: mix phx.routes [Router]
# Display all defined routes for debugging
# Mix Task: mix phx.gen.cert
# Generate SSL certificate for HTTPS development
# Mix Task: mix phx.gen.secret [length]
# Generate cryptographically secure secret keys
# Mix Task: mix phx.digest
# Compile and compress static assets for production
# Mix Task: mix phx.digest.clean [--all]
# Clean old digested assets# Start server with specific port and binding
PORT=4001 mix phx.server
# Display routes for specific router
mix phx.routes MyAppWeb.ApiRouter
# Generate self-signed certificate for development
mix phx.gen.cert
# Generate 64-byte secret key
mix phx.gen.secret 64
# Compile and compress static assets
mix phx.digest
# Clean old digested assets (keep 2 most recent)
mix phx.digest.clean
# Remove all digested assets
mix phx.digest.clean --all# Mix Task: mix phx.gen.release [options]
# Generates:
# - Release configuration
# - Docker files (optional)
# - Deployment scripts
# - Environment configuration# Basic release configuration
mix phx.gen.release
# With Docker support
mix phx.gen.release --docker
# For specific deployment target
mix phx.gen.release --target=fly# Context options
--no-context # Skip context generation
--context-app app # Generate context in different app
--merge-with-existing-context # Add to existing context
# Schema options
--no-schema # Skip schema generation
--binary-id # Use binary IDs instead of integers
--table name # Custom table name
# Web options
--web Module # Web module namespace (e.g., Admin)
--no-templates # Skip template generation
--no-views # Skip view generation
# Test options
--no-test # Skip test generation
# Migration options
--no-migration # Skip migration generationPhoenix generators use customizable templates that can be overridden:
# Copy default templates for customization
mix phx.gen.html --no-compile Blog Post posts title:string
# Templates are located in:
# priv/templates/phx.gen.html/
# priv/templates/phx.gen.context/
# priv/templates/phx.gen.schema/# Basic types
string text integer float decimal boolean
date time naive_datetime utc_datetime
uuid binary array map
# Type modifiers
:unique # Add unique constraint
:redact # Mark field as sensitive in logs
:primary_key # Mark as primary key
:references:table # Foreign key reference
# Array types
:array # PostgreSQL arrays
{:array, :string} # Array of strings
# Enum types
:enum:val1:val2:val3 # Enum with specific values
# Decimal precision
:decimal:precision:scale # decimal:10:2 for money# HTML generator creates:
lib/my_app/
blog/ # Context directory
post.ex # Schema
blog.ex # Context module
lib/my_app_web/
controllers/
post_controller.ex # Controller
templates/
post/
index.html.eex # Templates
show.html.eex
new.html.eex
edit.html.eex
form.html.eex
views/
post_view.ex # View module
test/
my_app/
blog_test.exs # Context tests
my_app_web/
controllers/
post_controller_test.exs # Controller tests
priv/repo/migrations/
*_create_posts.exs # Migration# Frontend asset compilation
npm run deploy --prefix ./assets
# Watch assets during development
npm run watch --prefix ./assets
# Custom esbuild configuration
mix assets.build
mix assets.watch# Generate migration only
mix ecto.gen.migration create_posts
# Generate from schema
mix phx.gen.schema Blog.Post posts title:string --migration-only
# Custom migration with references
mix phx.gen.context Blog Comment comments \
post_id:references:posts author:string body:text \
--foreign-key-type=uuidGenerated tests follow Phoenix testing conventions:
# Generated controller test
defmodule MyAppWeb.PostControllerTest do
use MyAppWeb.ConnCase
import MyApp.BlogFixtures
@create_attrs %{body: "some body", title: "some title"}
@update_attrs %{body: "updated body", title: "updated title"}
@invalid_attrs %{body: nil, title: nil}
describe "index" do
test "lists all posts", %{conn: conn} do
conn = get(conn, Routes.post_path(conn, :index))
assert html_response(conn, 200) =~ "Listing Posts"
end
end
describe "create post" do
test "redirects to show when data is valid", %{conn: conn} do
conn = post(conn, Routes.post_path(conn, :create), post: @create_attrs)
assert %{id: id} = redirected_params(conn)
assert redirected_to(conn) == Routes.post_path(conn, :show, id)
end
end
endInstall with Tessl CLI
npx tessl i tessl/hex-phoenix