CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/hex-phoenix

Peace of mind from prototype to production - comprehensive web framework for Elixir

Overview
Eval results
Files

code-generation.mddocs/

Code Generation and Development Tools

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.

Core Generators

Phoenix includes generators for all major application components, from basic schemas to complete authentication systems.

Authentication Generator

# 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

Usage Examples

# 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

Context and Schema Generators

# 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

Usage Examples

# 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

Web Interface Generators

# 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

Usage Examples

# 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 Admin

Real-time Generators

Phoenix provides specialized generators for real-time features and communication.

Channel Generator

# Mix Task: mix phx.gen.channel Channel [options]
# Generates:
# - Channel module with join/handle_in callbacks
# - Channel test file
# - Socket configuration (if needed)

Usage Examples

# Chat room channel
mix phx.gen.channel Room

# User notification channel
mix phx.gen.channel User

# Game lobby channel
mix phx.gen.channel GameLobby

Generated Channel Example

# 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

Socket Generator

# Mix Task: mix phx.gen.socket Socket [options]
# Generates:
# - Socket module with connect/id callbacks
# - Endpoint socket configuration

Usage Examples

# 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

Presence and Notification Generators

Presence Generator

# Mix Task: mix phx.gen.presence [Module] [options]
# Generates:
# - Presence module with tracking callbacks
# - Integration with PubSub system

Usage Examples

# User presence tracking
mix phx.gen.presence UserPresence

# Game room presence
mix phx.gen.presence GamePresence

Generated Presence Example

defmodule 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

Notifier Generator

# Mix Task: mix phx.gen.notifier Context Notifier [functions]
# Generates:
# - Notifier module with email/SMS functions
# - Templates for notifications
# - Tests for delivery functions

Usage Examples

# 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_email

Development Utilities

Phoenix provides various utilities for development, debugging, and deployment preparation.

Development Tasks

# 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

Usage Examples

# 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

Release Generator

# Mix Task: mix phx.gen.release [options]
# Generates:
# - Release configuration
# - Docker files (optional)
# - Deployment scripts
# - Environment configuration

Usage Examples

# 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

Generator Options and Customization

Common Generator Options

# 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 generation

Custom Templates

Phoenix 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/

Field Types and Modifiers

# 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

Generated File Structure

# 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

Integration with External Tools

Webpack and Asset Pipeline

# 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

Database Integration

# 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=uuid

Testing Integration

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

Install with Tessl CLI

npx tessl i tessl/hex-phoenix

docs

code-generation.md

index.md

presence.md

real-time.md

security.md

testing.md

web-foundation.md

tile.json