Usage of Repository pattern to make contexts thinner

ecto
phoenix

#1

Hello, folks! I just published article with the way how to cope with big context files by using repository pattern: https://medium.com/@Mike_Andr/thoughts-about-phoenix-and-repository-pattern-a0af5a8f0b9e

In short: move all db interactions from the context file to the repository and call it inside the context.
Please let me know what do you think about it! Is it fine or you can a better approach?


#2

If suggest looking at defdelegate.

Put your functions where you see fit. Doesn’t overly matter imho. As long as it’s clear to you and your team.

I’m personally of the opinion of your context is getting large either it can probably be split up into other contexts.


#3

Like @theangryangel said, take a look at defdelegate though personally I think that defdelegate should only be used to delegate t methods and functions from external packages.

Example

defmodule Novistore.Accounts.Authentication do
  @moduledoc """
  Authentication
  """

  @doc """
  Check the password against the password_hash
  """
  defdelegate check_password(password, password_hash), to: Comeonin.Bcrypt, as: :checkpw

  @doc """
  Dummy check password
  """
  defdelegate dummy_check_password, to: Comeonin.Bcrypt, as: :dummy_checkpw

  @doc """
  Hash the password
  """
  defdelegate hash_password(password), to: Comeonin.Bcrypt, as: :hashpwsalt
end

The above example allows me to switch out Bcrypt for Aragon2 in the future (if needed) without having to refactor the entire app.

I really like this article http://devonestes.herokuapp.com/a-proposal-for-context-rules by @devonestes for when you have to deal with large contexts.

We’ve adapted his idea’s at Novistore and I’m really happy with it.


#4

I like it. Helps keep context clear and concise.