A Peek at Phoenix in Elixir
Creating the Phoenix App
Here’s how to generate the scaffold Phoenix app we walked through in the video:
Step 1: Install Hex
Start by installing Hex (Elixir’s package manager) locally:
mix local.hex
If you already have a version of Hex installed, you’ll be asked whether you want to upgrade Hex to the latest version.
Step 2: Install the Phoenix Archive
Next, install the Phoenix archive:
mix archive.install hex phx_new 1.5.1
Step 3: Create a Phoenix Project
With Phoenix successfully installed, you can now create a Phoenix project. We named our project refuge:
mix phx.new refuge
You’ll see a list of files and directories created by the generator in a new refuge parent directory. Change into the refuge directory:
cd refuge
Step 4: Generate the Scaffold HTML App
Generate the scaffold HTML app using the phx.gen.html generator:
mix phx.gen.html Wildthings Bear bears name:string type:string hibernating:boolean
After running this command, open the refuge directory in your favorite editor to see all the code!
Route vs. Match Functions
Our route function currently takes one argument: a map representing the conversation. We pattern match the key-value pairs in the map. For example, here’s the route that matches a GET request for the path /bears:
def route(%Conv{ method: "GET", path: "/bears" } = conv) do
...
endBy comparison, here’s the match function generated by Phoenix:
def match(conn, "GET", ["/bears"]) do
...
endNotice it takes three arguments: conn (which is similar to our conversation map), the HTTP verb, and a list containing path segments.
Comparison to Our Route Design
Earlier in the course, our route/1 function looked very similar to the match function generated by Phoenix. We had a route/1 function that called a route/3 function:
def route(conv) do
route(conv, conv.method, conv.path)
endAnd here’s the route/3 function that matched a GET request for the path /bears:
def route(conv, "GET", "/bears") do
...
endThis is strikingly similar to the match function generated by Phoenix. The primary difference is that match takes a list of path segments as its third argument, which provides more information for pattern matching.
Experimenting with Designs
One of the reasons we chose a single map argument for the route function was to learn how to pattern match maps. However, now that you have seen both designs, you can experiment and decide which approach works better for you!
Code So Far
The code for this section is in the phoenix directory found within the video-code directory of the code bundle
Why always me?