0
# Code Generation and Development Tools
1
2
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.
3
4
## Core Generators
5
6
Phoenix includes generators for all major application components, from basic schemas to complete authentication systems.
7
8
### Authentication Generator
9
10
```elixir { .api }
11
# Mix Task: mix phx.gen.auth Context Schema table [fields] [options]
12
# Generates complete authentication system including:
13
# - User schema with password hashing
14
# - UserToken schema for session/reset tokens
15
# - Context with authentication functions
16
# - Controllers for registration, login, settings
17
# - Templates and views for all auth pages
18
# - Database migrations and tests
19
```
20
21
### Usage Examples
22
23
```bash
24
# Complete authentication system
25
mix phx.gen.auth Accounts User users name:string email:string:unique
26
27
# Custom confirmation field
28
mix phx.gen.auth Accounts User users email:string:unique \
29
--confirm-email --live
30
31
# With custom table name
32
mix phx.gen.auth Accounts User accounts email:string:unique
33
```
34
35
### Context and Schema Generators
36
37
```elixir { .api }
38
# Mix Task: mix phx.gen.context Context Schema table [fields]
39
# Generates context module with schema, database functions, and tests
40
41
# Mix Task: mix phx.gen.schema Context.Schema table [fields]
42
# Generates schema module only with changeset functions
43
44
# Mix Task: mix phx.gen.embedded Schema [fields]
45
# Generates embedded schema (no database table)
46
47
# Supported field types:
48
# :string, :text, :integer, :float, :decimal, :boolean
49
# :date, :time, :naive_datetime, :utc_datetime
50
# :uuid, :binary, :array, :map, :enum
51
```
52
53
### Usage Examples
54
55
```bash
56
# Blog context with posts and comments
57
mix phx.gen.context Blog Post posts title:string body:text published:boolean
58
mix phx.gen.context Blog Comment comments post_id:references:posts \
59
author:string body:text
60
61
# E-commerce product catalog
62
mix phx.gen.context Catalog Product products \
63
name:string description:text price:decimal:precision:10:scale:2 \
64
sku:string:unique category:enum:electronics:books:clothing
65
66
# User profile with embedded address
67
mix phx.gen.context Accounts Profile profiles \
68
user_id:references:users bio:text avatar_url:string
69
mix phx.gen.embedded Address street:string city:string state:string zip:string
70
```
71
72
### Web Interface Generators
73
74
```elixir { .api }
75
# Mix Task: mix phx.gen.html Context Schema table [fields] [options]
76
# Generates full CRUD HTML interface with controller, views, templates
77
78
# Mix Task: mix phx.gen.json Context Schema table [fields] [options]
79
# Generates JSON API interface with controller and JSON views
80
81
# Mix Task: mix phx.gen.live Context Schema table [fields] [options]
82
# Generates LiveView interface with real-time updates
83
84
# Common options:
85
# --no-context # Skip generating context
86
# --no-schema # Skip generating schema
87
# --web Module # Specify web module namespace
88
# --context-app # Generate context in different app
89
```
90
91
### Usage Examples
92
93
```bash
94
# Complete HTML CRUD for blog posts
95
mix phx.gen.html Blog Post posts title:string body:text \
96
published:boolean published_at:naive_datetime
97
98
# JSON API for mobile app
99
mix phx.gen.json Accounts User users name:string email:string \
100
--no-context
101
102
# Real-time LiveView interface
103
mix phx.gen.live Catalog Product products name:string price:decimal \
104
description:text in_stock:boolean
105
106
# Admin interface in separate namespace
107
mix phx.gen.html Blog Post posts title:string body:text \
108
--web Admin
109
```
110
111
## Real-time Generators
112
113
Phoenix provides specialized generators for real-time features and communication.
114
115
### Channel Generator
116
117
```elixir { .api }
118
# Mix Task: mix phx.gen.channel Channel [options]
119
# Generates:
120
# - Channel module with join/handle_in callbacks
121
# - Channel test file
122
# - Socket configuration (if needed)
123
```
124
125
### Usage Examples
126
127
```bash
128
# Chat room channel
129
mix phx.gen.channel Room
130
131
# User notification channel
132
mix phx.gen.channel User
133
134
# Game lobby channel
135
mix phx.gen.channel GameLobby
136
```
137
138
### Generated Channel Example
139
140
```elixir
141
# lib/my_app_web/channels/room_channel.ex
142
defmodule MyAppWeb.RoomChannel do
143
use Phoenix.Channel
144
145
@impl true
146
def join("room:lobby", payload, socket) do
147
if authorized?(payload) do
148
{:ok, socket}
149
else
150
{:error, %{reason: "unauthorized"}}
151
end
152
end
153
154
# Channels can be used in a request/response fashion
155
# by sending replies to requests from the client
156
@impl true
157
def handle_in("ping", payload, socket) do
158
{:reply, {:ok, payload}, socket}
159
end
160
161
# It is also common to receive messages from the client and
162
# broadcast to everyone in the current topic (room:lobby).
163
@impl true
164
def handle_in("shout", payload, socket) do
165
broadcast(socket, "shout", payload)
166
{:noreply, socket}
167
end
168
169
# Add authorization logic here as required.
170
defp authorized?(_payload) do
171
true
172
end
173
end
174
```
175
176
### Socket Generator
177
178
```elixir { .api }
179
# Mix Task: mix phx.gen.socket Socket [options]
180
# Generates:
181
# - Socket module with connect/id callbacks
182
# - Endpoint socket configuration
183
```
184
185
### Usage Examples
186
187
```bash
188
# User socket for authenticated connections
189
mix phx.gen.socket User
190
191
# Admin socket for management interface
192
mix phx.gen.socket Admin
193
194
# API socket for service-to-service communication
195
mix phx.gen.socket Api
196
```
197
198
## Presence and Notification Generators
199
200
### Presence Generator
201
202
```elixir { .api }
203
# Mix Task: mix phx.gen.presence [Module] [options]
204
# Generates:
205
# - Presence module with tracking callbacks
206
# - Integration with PubSub system
207
```
208
209
### Usage Examples
210
211
```bash
212
# User presence tracking
213
mix phx.gen.presence UserPresence
214
215
# Game room presence
216
mix phx.gen.presence GamePresence
217
```
218
219
### Generated Presence Example
220
221
```elixir
222
defmodule MyApp.UserPresence do
223
@moduledoc """
224
Provides presence tracking to channels and processes.
225
226
See the [`Phoenix.Presence`](http://hexdocs.pm/phoenix/Phoenix.Presence.html)
227
docs for more details.
228
"""
229
use Phoenix.Presence, otp_app: :my_app,
230
pubsub_server: MyApp.PubSub
231
end
232
```
233
234
### Notifier Generator
235
236
```elixir { .api }
237
# Mix Task: mix phx.gen.notifier Context Notifier [functions]
238
# Generates:
239
# - Notifier module with email/SMS functions
240
# - Templates for notifications
241
# - Tests for delivery functions
242
```
243
244
### Usage Examples
245
246
```bash
247
# User account notifications
248
mix phx.gen.notifier Accounts UserNotifier \
249
welcome_email reset_password_email account_locked_email
250
251
# Order notifications for e-commerce
252
mix phx.gen.notifier Orders OrderNotifier \
253
order_confirmed_email order_shipped_email order_delivered_email
254
```
255
256
## Development Utilities
257
258
Phoenix provides various utilities for development, debugging, and deployment preparation.
259
260
### Development Tasks
261
262
```elixir { .api }
263
# Mix Task: mix phx.server
264
# Start development server with live code reloading
265
266
# Mix Task: mix phx.routes [Router]
267
# Display all defined routes for debugging
268
269
# Mix Task: mix phx.gen.cert
270
# Generate SSL certificate for HTTPS development
271
272
# Mix Task: mix phx.gen.secret [length]
273
# Generate cryptographically secure secret keys
274
275
# Mix Task: mix phx.digest
276
# Compile and compress static assets for production
277
278
# Mix Task: mix phx.digest.clean [--all]
279
# Clean old digested assets
280
```
281
282
### Usage Examples
283
284
```bash
285
# Start server with specific port and binding
286
PORT=4001 mix phx.server
287
288
# Display routes for specific router
289
mix phx.routes MyAppWeb.ApiRouter
290
291
# Generate self-signed certificate for development
292
mix phx.gen.cert
293
294
# Generate 64-byte secret key
295
mix phx.gen.secret 64
296
297
# Compile and compress static assets
298
mix phx.digest
299
300
# Clean old digested assets (keep 2 most recent)
301
mix phx.digest.clean
302
303
# Remove all digested assets
304
mix phx.digest.clean --all
305
```
306
307
### Release Generator
308
309
```elixir { .api }
310
# Mix Task: mix phx.gen.release [options]
311
# Generates:
312
# - Release configuration
313
# - Docker files (optional)
314
# - Deployment scripts
315
# - Environment configuration
316
```
317
318
### Usage Examples
319
320
```bash
321
# Basic release configuration
322
mix phx.gen.release
323
324
# With Docker support
325
mix phx.gen.release --docker
326
327
# For specific deployment target
328
mix phx.gen.release --target=fly
329
```
330
331
## Generator Options and Customization
332
333
### Common Generator Options
334
335
```bash { .api }
336
# Context options
337
--no-context # Skip context generation
338
--context-app app # Generate context in different app
339
--merge-with-existing-context # Add to existing context
340
341
# Schema options
342
--no-schema # Skip schema generation
343
--binary-id # Use binary IDs instead of integers
344
--table name # Custom table name
345
346
# Web options
347
--web Module # Web module namespace (e.g., Admin)
348
--no-templates # Skip template generation
349
--no-views # Skip view generation
350
351
# Test options
352
--no-test # Skip test generation
353
354
# Migration options
355
--no-migration # Skip migration generation
356
```
357
358
### Custom Templates
359
360
Phoenix generators use customizable templates that can be overridden:
361
362
```bash
363
# Copy default templates for customization
364
mix phx.gen.html --no-compile Blog Post posts title:string
365
366
# Templates are located in:
367
# priv/templates/phx.gen.html/
368
# priv/templates/phx.gen.context/
369
# priv/templates/phx.gen.schema/
370
```
371
372
### Field Types and Modifiers
373
374
```bash { .api }
375
# Basic types
376
string text integer float decimal boolean
377
date time naive_datetime utc_datetime
378
uuid binary array map
379
380
# Type modifiers
381
:unique # Add unique constraint
382
:redact # Mark field as sensitive in logs
383
:primary_key # Mark as primary key
384
:references:table # Foreign key reference
385
386
# Array types
387
:array # PostgreSQL arrays
388
{:array, :string} # Array of strings
389
390
# Enum types
391
:enum:val1:val2:val3 # Enum with specific values
392
393
# Decimal precision
394
:decimal:precision:scale # decimal:10:2 for money
395
```
396
397
### Generated File Structure
398
399
```
400
# HTML generator creates:
401
lib/my_app/
402
blog/ # Context directory
403
post.ex # Schema
404
blog.ex # Context module
405
406
lib/my_app_web/
407
controllers/
408
post_controller.ex # Controller
409
templates/
410
post/
411
index.html.eex # Templates
412
show.html.eex
413
new.html.eex
414
edit.html.eex
415
form.html.eex
416
views/
417
post_view.ex # View module
418
419
test/
420
my_app/
421
blog_test.exs # Context tests
422
my_app_web/
423
controllers/
424
post_controller_test.exs # Controller tests
425
426
priv/repo/migrations/
427
*_create_posts.exs # Migration
428
```
429
430
## Integration with External Tools
431
432
### Webpack and Asset Pipeline
433
434
```bash
435
# Frontend asset compilation
436
npm run deploy --prefix ./assets
437
438
# Watch assets during development
439
npm run watch --prefix ./assets
440
441
# Custom esbuild configuration
442
mix assets.build
443
mix assets.watch
444
```
445
446
### Database Integration
447
448
```bash
449
# Generate migration only
450
mix ecto.gen.migration create_posts
451
452
# Generate from schema
453
mix phx.gen.schema Blog.Post posts title:string --migration-only
454
455
# Custom migration with references
456
mix phx.gen.context Blog Comment comments \
457
post_id:references:posts author:string body:text \
458
--foreign-key-type=uuid
459
```
460
461
### Testing Integration
462
463
Generated tests follow Phoenix testing conventions:
464
465
```elixir
466
# Generated controller test
467
defmodule MyAppWeb.PostControllerTest do
468
use MyAppWeb.ConnCase
469
470
import MyApp.BlogFixtures
471
472
@create_attrs %{body: "some body", title: "some title"}
473
@update_attrs %{body: "updated body", title: "updated title"}
474
@invalid_attrs %{body: nil, title: nil}
475
476
describe "index" do
477
test "lists all posts", %{conn: conn} do
478
conn = get(conn, Routes.post_path(conn, :index))
479
assert html_response(conn, 200) =~ "Listing Posts"
480
end
481
end
482
483
describe "create post" do
484
test "redirects to show when data is valid", %{conn: conn} do
485
conn = post(conn, Routes.post_path(conn, :create), post: @create_attrs)
486
487
assert %{id: id} = redirected_params(conn)
488
assert redirected_to(conn) == Routes.post_path(conn, :show, id)
489
end
490
end
491
end
492
```