Skip to content

Instantly share code, notes, and snippets.

@s-espinosa
Created December 28, 2017 19:20
Show Gist options
  • Save s-espinosa/a17c904136ff5d11c3542e5fdb5c0a51 to your computer and use it in GitHub Desktop.
Save s-espinosa/a17c904136ff5d11c3542e5fdb5c0a51 to your computer and use it in GitHub Desktop.

From the Command Line

Action Command
Start a New Project mix phx.new project_name
Create DB mix ecto.create
Start App mix phx.server
Run App in Interactive Elixir (IEx) iex -S mix phx.server
Show Routes mix phx.routes

File Structure

  • lib/project_name_web
    • Main application files.
    • Directories for controllers, templates, and views live here.
    • router.ex also lives here.
  • assets
    • Static assets
    • Compiled to priv/static
  • Questions
    • What goes in lib/app_name?
    • How is it different from what goes in lib/app_name_web?

Core Files

Router

  • lib/project_name_web/router.ex
  • verb "path", SomeController, :some_action
  • resources "/some_resource", SomeResourceController, only: [:index, :show]
  • Can also use except.

Controllers

  • Controller syntax:
defmodule AppNameWeb.SomeController do
  use AppNameWeb, :controller

  def index(conn, _params) do
    render conn, "index.html"
  end
end
  • Leading _ on params required to avoid compiler warnings if we aren't using params in the controller action.
  • index.html.eex is a template in the templates directory (lib/app_name_web/templates/some assuming this is an action living in SomeController).

Views

  • Render templates.
  • Presentation layer for raw data from the controller.
  • SomeView goes with SomeController
  • Syntax in lib/app_name_web/views/some_view.ex
defmodule AppName.SomeView do
  use AppName, :view
end

Templates

  • .eex (Embedded Elixir)
  • lib/app_name_web/templates/some_name/index.html.eex syntax:
  • Path helpers: <a href="<%= page_path(@conn, :index) %>">To the Welcome Page!</a>
    • page_path(@conn, :show, 14)
    • page_path(@conn, :new)
    • page_path(@conn, :create)
    • page_path(@conn, :edit, 17)
    • page_path(@conn, :update, 17)
    • page_path(@conn, :delete, 24)
    • page_path(@conn, :show, 14, admin: true, some_other_opt: "some value")
<div class="jumbotron">
  <h2>Hello World, from Phoenix!</h2>
</div>
  • Template wrapper lives in lib/app_name_web/templates/layout/app.html.eex. Renders a partial with something like <%= render @view_module, @view_template, assigns %>

Ecto

  • Installation:
  • Add to mix.exs:
defp deps do
  [{:ecto, "~> 2.0"},
   {:postgrex, "~> 0.11"}]
end
  • mix deps.get

Stuff for Later

  • lib/hello/application.ex starts the Elixir application.
  • lib/hello/repo.ex: Ecto repo for interacting with the database.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment