Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Intro to Phoenix & Elixir

Intro to Phoenix & Elixir

Jakob Højgaard

September 16, 2016
Tweet

More Decks by Jakob Højgaard

Other Decks in Programming

Transcript

  1. WHAT IS ELIXIR Elixir is a dynamic, functional language designed

    for building scalable and maintainable applications. Elixir leverages the Erlang VM, known for running low-latency, distributed and fault- tolerant systems, while also being successfully used in web development and the embedded so ware domain. From elixir-lang.org
  2. ERLANG AND BEAM Erlang is a general purpose, concurrent functional

    programming language created at Ericsson in the mid 80'ies as a new language for programming phone switches Designed by Joe Armstrong, Robert Virding, and Mike Williams
  3. ERLANG AND BEAM - CONT. Designed for Distribution Fault-tolerance High

    availability Hot code swapping Complies to bytecode and runs on the Erlang VM (BEAM) OTP provides useful middleware, libraries and tools (GenServer)
  4. Created by José Valim Full inter-operation with Erlang More or

    less shared type system with Erlang Ruby inspired syntax (on the surface) Steals great things from any language
  5. TYPES iex> 1 # integer iex> 0x1F # integer iex>

    1.0 # float iex> true # boolean iex> :atom # atom / symbol iex> "elixir" # string iex> [1, 2, 3] # list iex> {1, 2, 3} # tuple
  6. OPERATORS Elixir supports the usual basic arithmetic operators like +,

    -, * and / ++ and -- are used to manipulate lists String concatenation are done with <> Comparing types are also possible, like iex> 1 < :atom true
  7. FUNCTIONS AND MODULES defmodule EnterpriseMath do def add(a, b) do

    do_add(a,b) end defp do_add(a, b) do a + b end end By conversion Elixir uses snake_case but module name are CamelCase.
  8. ANONYMOUS FUNCTIONS # Elixir also supports anonymous times_two = fn

    (a) -> a * 2 end two_times_two = times_two.(2) # But there is also a shorthand notation using the & times_three = &(&1 * 3) three_times_three = times_three.(3)
  9. COLLECTIONS # Keyword lists iex> list = [{:a, 1}, {:b,

    2}] [a: 1, b: 2] iex> list == [a: 1, b: 2] true # Maps iex> map = %{:a => 1, 2 => :b} %{2 => :b, :a => 1} iex> map[:a] 1
  10. STRUCTS Structs are like maps, with a predefined set of

    fields defmodule Book do defstruct title: "", author: "" end # Create a book iex>the_trial = %Book{title: "The Trial", author: "Franz Kafka"} %Book{author: "Franz Kafka", title: "The Trial"} # Access fields iex>the_trial.title The Trial # In fact structs are just maps with a special property __struct__ iex>the_trial.__struct__ Book
  11. UNLEARN THE EQUAL SIGN “Joe Armstrong, Erlang’s creator, compares the

    equals sign in Erlang to that used in algebra. When you write the equation x = a + 1, you are not assigning the value of a + 1 to x. Instead you’re simply asserting that the expressions x and a + 1 have the same value. If you know the value of x, you can work out the value of a, and vice versa.” from "Programming Elixir 1.3"
  12. THE MATCH OPERATOR = iex>x = 1 1 iex>x 1

    iex>1 = x 1 # lists iex> list = [1, 2, 3] [1, 2, 3] iex> [a, b, c ] = list [1, 2, 3] iex>a 1
  13. FUNCTION SIGNATURES defmodule Humanize do def join([]), do: "" def

    join([head | []]), do: head def join([head | [tail | [] ]]), do: head <> " and " <> tail def join([head | tail]), do: head <> ", " <> join(tail) end
  14. CONTROL STRUCTURES - CASE # case is like the match

    of F# defmodule Humanize do def join(list) do case list do [] -> "" [head | []] -> head [head | [tail | [] ]] -> head <> " and " <> tail [head | tail] -> head <> " , " <> join(tail) end end end
  15. CONTROL STRUCTURES - COND # cond can be arbitrary matches

    iex> cond do ...> 2 + 2 == 5 -> ...> "This is never true" ...> 2 * 2 == 3 -> ...> "Nor this" ...> true -> ...> "This is always true (equivalent to else)" ...> end "This is always true (equivalent to else)"
  16. CONTROL STRUCTURES - IF & UNLESS iex> if true do

    ...> "This works!" ...> end "This works!" iex> unless true do ...> "This will never be seen" ...> end nil
  17. THE PIPELINE OPERATOR The pipeline operator is one of the

    features that is stolen from another language (F#) The pipeline operator pipes the result of one function onto the first parameter od the next function in the pipeline (2..11) |> Enum.map(&(Integer.to_string(&1))) |> Enum.map(&(&1 <> " cases of beer")) |> Enum.map(&(IO.puts &1))
  18. PROCESSES In elixir everything lives inside a process Lightweight -

    unlike OS processes Processes are isolated from each other Communicates with other processes through messages Start new process with spawn Can be linked to process by link or spawn_link
  19. PROCESSES - CONTINUED iex> pid = spawn fn -> IO.puts

    "Time for beer yet?" end #PID<0.84.0> iex> Process.alive?(pid) false iex> Process.alive?(self()) true # Send receive iex> parent = self() #PID<0.41.0> iex> spawn fn -> send(parent, {:hello, self()}) end #PID<0.48.0> iex> receive do ...> {:hello, pid} -> "Got hello from #{inspect pid}" ...> end "Got hello from #PID<0.48.0>"
  20. IEX The Elixir REPL $>iex Erlang/OTP 19 [erts-8.0.2] [source] [64-bit]

    [smp:8:8] [async-threads:10] [hipe] [kernel-poll:false] [dtrace] Interactive Elixir (1.3.2) - press Ctrl+C to exit (type h() ENTER for help) iex(1)>self #PID<0.80.0>
  21. MIX $> mix help mix # Runs the default task

    (current: "mix run") mix app.start # Starts all registered apps mix app.tree # Prints the application tree mix archive # Lists installed archives mix archive.build # Archives this project into a .ez file mix archive.install # Installs an archive locally mix archive.uninstall # Uninstalls archives mix clean # Deletes generated application files mix cmd # Executes the given command mix compile # Compiles source files mixie deps # Lists dependencies and their status ... mix run # Runs the given file or expression mix test # Runs a project's tests iex -S mix # Starts IEx and runs the default task
  22. PROJECT STRUCTURE $>mix new beerapp * creating README.md * creating

    .gitignore * creating mix.exs * creating config * creating config/config.exs * creating lib * creating lib/beerapp.ex * creating test * creating test/test_helper.exs * creating test/beerapp_test.exs Your Mix project was created successfully.
  23. A MODERN WEB FRAMEWORK A productive web framework that does

    not compromise speed and maintainability.
  24. MVC OF PHOENIX connection # Plug.Conn |> endpoint # lib/hello/endpoint.ex

    |> browser # web/router.ex |> HelloController.world # web/controllers/hello_controller.ex |> HelloView.render( # web/views/hello_view.ex "world.html") # web/templates/hello/world.html.eex
  25. WHAT DID I LEAVE OUT Lots of Phoenix (channels) Ecto

    Nerves (IOT) Clustering (scaling out) Loads more I still don't know about