我应该在Elixir Phoenix的控制器或模型中使用Ecto.Repo吗? [英] Should I use Ecto.Repo in Controller or Model for Elixir Phoenix?

查看:47
本文介绍了我应该在Elixir Phoenix的控制器或模型中使用Ecto.Repo吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于 Phoenix 的控制器中的某些查询,有两个针对我的计划

For some query in Controller of Phoenix, there're two plans for me

计划1:

defmodule Demo.UserController do
  # ...
  def index do
    # This is just for example
    # The point is Repo in used here
    Repo.all(User) 
  end
end

计划2:

defmodule Demo.User do
  # ...
  def all do
    # Put all Repo API and building query logic in Model
    Repo.all(__MODULE__)
  end
end

我更喜欢计划2.因为在大多数情况下,我都可以将所有关于获取数据的逻辑放在模型中.

I prefer the Plan 2. Because in most situations, I can put all logic about fetching data in Model.

但是我发现官方指南使用计划1( docs/model )和Phoenix默认代码alias Repo在控制器中而不是模型中(网络/web.ex )

But I find official guide use Plan 1(docs/model) and Phoenix default code alias Repo in Controller instead of Model (web/web.ex)

哪个更好?为什么呢?

推荐答案

您应将Repo调用保留在控制器内.如果您的逻辑很复杂,则应考虑将逻辑移到其自己的服务模块中.

You should keep your Repo calls inside your controller. If your logic is complicated then you should consider moving the logic out into its own service module.

您应该将模型函数视为纯函数(无副作用),因此它们应仅对数据起作用.因此,例如,您可以:

You should treat your model functions as pure (free from side effects) so they should only act on data. So for example you could have:

def alphabetical(query)
  order_by(query, [u], u.name)
end

但是您不应该拥有:

def alphabetical(query)
  order_by(query, [u], u.name)
  |> Repo.all
end

这是因为查询纯粹是数据,对Repo.all的调用具有副作用(将转到数据库),因此它属于您的控制器.

This is because queries are purely data, the call to Repo.all has side effects (going off to the database) so it belongs in your controller.

这篇关于我应该在Elixir Phoenix的控制器或模型中使用Ecto.Repo吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆