Context

The Model in traditional MVC frameworks are splited into context and schema in Phoenix.

Scaffolding

Following command will generate a full CRUD API for a Post resource inside a Blog context.

mix phx.gen.json Blog Post posts title:string content:text

The command will genrate a bunch of files,

* lib/app1_web/controllers/post_controller.ex
* lib/app1_web/controllers/post_json.ex
* lib/app1_web/controllers/changeset_json.ex
* lib/app1_web/controllers/fallback_controller.ex
* lib/app1/blog/post.ex
* lib/app1/blog.ex
...
more db migration and other test related files

Add a routing rule to the "/api" scope in lib/app1_web/router.ex:

resources "/posts", PostController, except: [:new, :edit]

Then run mix ecto.migrate to apply the database schema changes.

The API should be ready.

curl localhost:4000/api/posts

Will return:

{"data":[]}

Context

What is a context? Take a look at lib/app1/blog.ex. It containers following functions:

  • list_posts
  • get_post
  • create_post
  • update_post
  • delete_post
  • change_post

And in those functions, App1.Repo is invoke to talk to database:

def list_posts do
  Repo.all(Post)
end

Here Post is a schema module defined in lib/app1/blog/post.ex.

In Phoenix, it's

Controller → Context → Repo → Schema

In Spring, it's

Controller → Service → Repository → Entity