MVC: calling the Database in the controller or in the model???

I’m a teaching students to start working as a Junior Programmer. We want to teach the kids functional programming with elixir. The students have some programming experience in PHP, javascript, HTML,…
We are creating a course in functional programming with elixir and we need to teach them MVC.

Let say: we want a function that asks the db, 10 customers with the highest revenue.

Should we put the function to the Controller or put the function to the model ???

Thanks! :Hans Odijk

1 Like

Phoenix generators put this in the “context”, which is something of a glue layer between the data types (your Ecto schemas) and controllers (or view-controllers (or …)).

So, you have something like:

lib/teaching/students/student.ex
# << some student model via etco or anything>>
defmodule Teaching.Students.Student do
  use Ecto.Schema
  #...
end
lib/teaching/students.ex
# "context" file
defmodule Teaching.Students do
  def list_students() do
    from(Students) |> Repo.all()
  end
end
lib/teaching_web/<controller-or-liveview>
defmodule TeachingWeb.<controller or liveview> do
  def something()
    students = Teaching.Students.list_students()
  end
end

Checkout the default project generated by phoenix for more complete examples. Probably simplest to just stick with the layout given by the generators when teaching the basics.

2 Likes

While DDD is an interesting topic bounded contexts are quite a different beast to what phoenix contexts are – which is funny given DDD teaches that the same words might mean different things in different contexts. I’d advice to keep DDD out of questions about code structure. DDD is much more about logical boundries than code.

To answer the question: You don’t want to couple business logic with controllers. Optimally you want an “elixir application” – as in a code base as much as possible unaware it’s being accessed via http/the web. And then you put controllers aside of it, which call into that application to make things work for http requests. Phoenix contexts are one way to structure that elixir application.

10 Likes

THX, answers are clear :man_teacher: