24
Realtime Web Apps with Elixir and Phoenix Brian P. Hogan

Realtime Web Apps With Elixir And Phoenix

Embed Size (px)

Citation preview

Page 1: Realtime Web Apps With Elixir And Phoenix

Realtime Web Appswith Elixir and Phoenix

Brian P. Hogan

Page 2: Realtime Web Apps With Elixir And Phoenix

Brian P. Hogan@bphogan

http://bphogan.com/presentations/phoenix

Today

• Build a simple text-collaboration web app

• Explore a little Elixir

• Explore some ES6.

Today you’ll learn about what Phoenix is and how it works as we work through a web application together. You’ll also learn a little about the Elixir language, and we’ll see some ES6 too, since Phoenix supports that out of the box.

Page 3: Realtime Web Apps With Elixir And Phoenix

Brian P. Hogan@bphogan

http://bphogan.com/presentations/phoenix

Me?

• I love to make web stuff

• I love to make music

• I love to teach

So, who am I? I’m a web developer and a teacher. I’m also a book author. I’ve been working with Phoenix for about 6 months now and Elixir for just under a year. I do most of my primary development with Ruby on Rails.

Page 4: Realtime Web Apps With Elixir And Phoenix

Brian P. Hogan@bphogan

http://bphogan.com/presentations/phoenix

• A functional programming language.

• Built on Erlang’s virtual machine.

• Multiprocessor and fast.

• Elegant.

So what’s Elixir? It’s a functional programming language that’s really new. It borrows some syntactical things from Ruby but leverages the speed and stability of Erlang. It’s a very powerful language because it can also give us access to the vast array of Erlang libraries available.

Page 5: Realtime Web Apps With Elixir And Phoenix

Brian P. Hogan@bphogan

http://bphogan.com/presentations/phoenix

• An MVC web framework

• Built for the “internet of things”

• Scalable and fast!

• Fault-tolerant

• Built-in support for web sockets

Phoenix is a web framework created by Chris McCord, designed to handle many connections and be scalable and fault tolerant. It’s nearing version 1.0 and has some pretty robust features including out-of-the-box support for web sockets.

Page 6: Realtime Web Apps With Elixir And Phoenix

Brian P. Hogan@bphogan

http://bphogan.com/presentations/phoenix

Our App

Today I’m going to build a small application that lets us create a text editor that broadcasts its content across the web. Anyone with the editor can type text and push that to any other connected editor.

Page 7: Realtime Web Apps With Elixir And Phoenix

Brian P. Hogan@bphogan

http://bphogan.com/presentations/phoenix

Getting Elixir and Phoenix

• Install Elixir from http://elixir-lang.org/install.html

• Install Phoenix from http://phoenixframework.org

• $ mix phoenix.new <path_to_app>

• $ cd <path_to_app>

• $ mix phoenix.server

To get started with Phoenix, you first need to install Elixir, which will have you install Erlang. Then you need to install Phoenix, which isn’t terribly hard now, but will get much easier in about a month. Just follow the directions on the Phoenix web site for now. Once you have things installed you run a command to create a new app, then change to the new directory that ets created and start the server.

Page 8: Realtime Web Apps With Elixir And Phoenix

Brian P. Hogan@bphogan

http://bphogan.com/presentations/phoenix

The whole process looks like this. The task creates the folder structure for you and sets up dependencies. Phoenix apps use Brunch to manage the client-side assets, which means we have support for Sass and Babel built in.

Page 9: Realtime Web Apps With Elixir And Phoenix

Brian P. Hogan@bphogan

http://bphogan.com/presentations/phoenix

PhoenixRouter

Controller Controller

View View

Template Template Template

Channel

Phoenix supports the traditional MVC pattern on the web, where we have a router route requests to a controller which then prepares a view and renders a template. In Phoenix, Views control what gets rendered, and Templates are what people see.

Page 10: Realtime Web Apps With Elixir And Phoenix

Brian P. Hogan@bphogan

http://bphogan.com/presentations/phoenix

PhoenixRouter

Controller Controller

View View

Template Template Template

Channel

We can also have the view render some data like JSON or XML without using a template by creating our own custom handlers.

Page 11: Realtime Web Apps With Elixir And Phoenix

Brian P. Hogan@bphogan

http://bphogan.com/presentations/phoenix

PhoenixRouter

Controller Controller

View View

Template Template Template

Channel

Phoenix also has Channels, which make it possible to send realtime data to connected clients using Websockets. Those clients can send data back to these channels in realtime as well. Clients subscribe to a Topic within a channel, and the server manages the connections.

Page 12: Realtime Web Apps With Elixir And Phoenix

Brian P. Hogan@bphogan

http://bphogan.com/presentations/phoenix

Elixir Basics

• Basic Types

• Pattern Matching

• Functions

• Piping

Let’s look at the basics of Elixir. This isn’t an Elixir talk, but we have some time while our app does its initial compilation.

Page 13: Realtime Web Apps With Elixir And Phoenix

Brian P. Hogan@bphogan

http://bphogan.com/presentations/phoenix

Basic Types1 # integer 0x1F # integer 1.0 # float true # boolean :atom # atom / symbol "elixir" # string [1, 2, 3] # list {:ok, “200 OK”} # tuple

Elixir has these data types, and a few more that we’re not gonna talk about today. It has integers, floating point numbers, booleans, atoms, which are just pieces of data we can use to label things. It also has strings. Finally, it has lists, which act like arrays, and tuples. Lists are linked-lists, so modifying them is easy if we add to the front, and tuples are usually reserved for fixed sets of data. Lots of functions return tuples in Elixir.

Page 14: Realtime Web Apps With Elixir And Phoenix

Brian P. Hogan@bphogan

http://bphogan.com/presentations/phoenix

Pattern Matching# Variable assignment age = 42

Elixir makes heavy use of pattern matching. First, it uses pattern matching to assign variables. When we assign the value of 42 to the “age” variable, Elixiir figures out how to make the left hand side match the right hand

Page 15: Realtime Web Apps With Elixir And Phoenix

Brian P. Hogan@bphogan

http://bphogan.com/presentations/phoenix

Pattern Matching# Variable assignment age

# We can destructure lists [first, second, third] = [1,2,3]

We can use that to break apart lists into individual variables. We just assign a list of variables to a list of values.

Page 16: Realtime Web Apps With Elixir And Phoenix

Brian P. Hogan@bphogan

http://bphogan.com/presentations/phoenix

Pattern Matching# Variable assignment age

# Many functions return tuples we can parse {number, junk} = Float.parse("123abc")

# We can destructure lists [first, second, third]

This works for tuples too. The Float.parse function returns a two-value tuple containing the numerical piece followed by the non-numerical part. We can capture that result into variables so we can easily discard the piece we don’t care about.

Page 17: Realtime Web Apps With Elixir And Phoenix

Brian P. Hogan@bphogan

http://bphogan.com/presentations/phoenix

Pattern Matching# Variable assignment age

# We can even pattern match strings "/products/" <> id = "/products/1234"

# Many functions return tuples we can parse {number, junk}

# We can destructure lists [first, second, third]

Finally, we can even do this with strings. We can pluck out part of a string. The <> is just the string concatenation character.

Page 18: Realtime Web Apps With Elixir And Phoenix

Brian P. Hogan@bphogan

http://bphogan.com/presentations/phoenix

Functions# A simple function add = fn(first, second) -> first + second end # A simple function using pattern matching tax = fn (amount, "WI") -> amount * 0.05 (amount, "MN") -> amount * 0.06 (amount, 0) -> 0 end

We can define some quick functions using the fn keyword. We can even define functions that match different incoming arguments. Depending on which signature matches, the function will run the appropriate code. In Elixir, the last expression executed is the return value. No need for explicit returning.

Page 19: Realtime Web Apps With Elixir And Phoenix

Brian P. Hogan@bphogan

http://bphogan.com/presentations/phoenix

Functionsdefmodule Math do def add(first, second) do first + second end end defmodule Tax do def calculate(amount, "WI"), do: amount * 0.05 def calculate(amount, "MN"), do: amount * 0.06 def calculate(amount, state), do: amount end

Our functions are usually organized into modules. We can define methods with a block syntax, or, if the method body only has one line, we can use a shorter one-line syntax. It’s our choice.

Page 20: Realtime Web Apps With Elixir And Phoenix

Brian P. Hogan@bphogan

http://bphogan.com/presentations/phoenix

Piping# Add up only even numbers Enum.reduce(Enum.filter([1,2,3,4,5,6], fn(x) -> rem(x, 2) == 0 end), 0, fn(x, acc) -> x + acc end )

Let’s add up all the even numbers in a list. First, we have to filter out all the even numbers by using Elixir’s Enum.filter function. Then we use Enum.reduce to sum up the elements in the list. Filter and reduce are pretty common nowadays, as you can use them in JavaScript, Ruby, and many other languages. But this is pretty hard to read. We could resort to using intermediate variables, but that isn’t the “functional” way. We want to make data flow through our program without using state unless we have no choice. And we do have a choice here.

Page 21: Realtime Web Apps With Elixir And Phoenix

Brian P. Hogan@bphogan

http://bphogan.com/presentations/phoenix

Piping# Add up only even numbers Enumrem(x, # Piping cleans this up [1,2,3,4,5,6] |> Enum.filter(fn(x) -> rem(x, 2) == 0 end) |> Enum.reduce(0, fn(x, acc) -> x + acc end)

But we can rearrange this using Pipes. In Elixir, we can pipe the output of one function to the first argument of another function. This lets us express our algorithms as a series of steps instead of a series of nested parentheses, resulting in more readable code.

Page 22: Realtime Web Apps With Elixir And Phoenix

Brian P. Hogan@bphogan

http://bphogan.com/presentations/phoenix

Let’s Build An App!

Page 23: Realtime Web Apps With Elixir And Phoenix

Brian P. Hogan@bphogan

http://bphogan.com/presentations/phoenix

Where to go next?

• Programming Elixir (https://pragprog.com/book/elixir/programming-elixir)

• #elixir-lang on IRC (Freenode)

• Phoenix Guides (http://www.phoenixframework.org/v0.11.0/docs/overview)

Page 24: Realtime Web Apps With Elixir And Phoenix

Brian P. Hogan@bphogan

http://bphogan.com/presentations/phoenix

Thanks!

• Twitter: @bphogan

• http://spkr8.com/t/57991

http://webdevelopmentrecipes.com/