rubynho

rubynho

Any idea of what code to put in the domain's main file

Context

Generating a phoenix app with name foo, an empty module will be created in the foo/lib/foo.ex file like so:

defmodule Foo do
  @moduledoc """
  Foo keeps the contexts that define your domain
  and business logic.

  Contexts are also responsible for managing your data, regardless
  if it comes from the database, an external API or others.
  """
end

That is what I’m calling the main file.

Question

What code do you put in there or any idea of what could fit?

In my mind it makes sense to put functions that use other functions from the contexts modules to deliver a complete service/feature of the system (e.g. user registration). For example:

defmodule Foo do
  alias Foo.Accounts

  def register_user(params)
    case Accounts.register_user(params) do
      {:ok, user} -> 
        Accounts.deliver_user_confirmation_instructions(
          user,
          &Path.join(params["confirmation_url"], &1)
        )

        {:ok, user}

      {:error, _} = error -> 
        error
    end
  end
end

See any cons about this idea?

Marked As Solved

sodapopcan

sodapopcan

To me the functions that would most naturally live here are delegates to every single public function in your domain. This is pretty heavy-handed, though, and I wouldn’t recommend it—I tried it! Otherwise, what you’re suggesting at the very least hurts discoverability. If you think of it from the perspective of someone coming in and only reading the business domain code, there will be auth functions spread out over different context boundaries. I don’t think it’s the worst thing in the world, but to me I would just think there is no point—just add a function to Accounts called register_and_notify_user. I would also change the signature to take user_attrs and confirmation_url separately.

Really in a Phoenix app, I think the best use of this module is documentation. I’m sure there is something that could naturally fit here, but I’ve never come across anything. I think a lot of people get perturbed that this file sits there devoid of code. It doesn’t personally bother me. If you use ex_doc on your project it certainly comes in handy!

Also Liked

tomkonidas

tomkonidas

I personally like to use it similar to the way Phoenix does it with the FooWeb module; As a place to define macros for your app.

A good example would be something like:

defmodule Foo.Accounts.User do
  use Foo, :schema
  
  schema "users" do
    # ...
  end
end

Which Foo can have something like:

defmodule Foo do
  def schema do
    quote do
      use Ecto.Schema
      import Ecto.Changeset

      @primary_key {:id, :binary_id, autogenerate: true}
      @foreign_key_type :binary_id
      @timestamps_opts [type: :utc_datetime_usec]
    end
  end

  defmacro __using__(which) when is_atom(which) do
    apply(__MODULE__, which, [])
  end
end
kokolegorille

kokolegorille

There is this package that does CQRS/ES

I did my own event store…

https://github.com/kokolegorille/event_store

and a simple demo usage

https://github.com/kokolegorille/microservices_umbrella

This allows me to decouple context… instead of doing

def register_user(...) do
  do_work()
  deliver_user_confirmation_instructions()
  notify_by_email()
end

I do

def register_user(...) do
  do_work()
  EventStore.create_event(...)
end

Any context can listen to any event…
register_user() does not need to know what to do when a user register
Adding functionalities is easier, because it does not affect previous code

When You create an event, it is dispatched to listeners

  def dispatch(event) do
    Logger.info("DISPATCH EVENT : #{inspect(event)}")

    ListenersProvider.get_listeners()
    |> Enum.filter(fn {_pid, filter_fun} -> filter_fun.(event) end)
    |> Enum.each(fn {pid, _apply_fun} -> send(pid, event) end)
    :ok
  end
cevado

cevado

I usually move whatever is on Foo.Application to Foo and update my mix.exs file to reflect that.
if it’s a phoenix app i usually rename FooWeb to be only Web and I rename the remaining stuff in the foo folder to be core and have a Core namespace.

but that’s because i really don’t how namespaces work in the default generators for plain mix or phoenix.

Where Next?

Popular in Questions Top

Darmani72
If I have a post route which an argument: post /my_post_route/:my_param1, MyController.my_post_handler How would get the post params ...
New
baxterw3b
Hi guys, i’m new in the Elixir world, and i have to say, that i love it! i’m having some problem to understand anonymous functions with ...
New
chrisalley
ExUnit now has describe blocks which is a welcome addition coming from RSpec. In the docs, it states that nested hierarchies of describe ...
New
mgjohns61585
Could someone help me? I’m making my first elixir program, number guessing game. I can’t figure out how to convert the user’s guess from ...
New
JulienCorb
I am trying to implement my new.html.eex file to create new posts on my website. new.html.eex: <h1>Create Post</h1> <%= ...
New
SoCreat
i’m a new one to elixir which editor can i use vs code? or atom? Thanks! :smiley:
New
RisingFromAshes
I’ve read in another post that it may be possible with a router helper - but I couldn’t find an appropriate one, and tbh, I’m still just ...
New
ashish173
I am using Ecto timestamps with postgres, I can see the timestamps() use the :naive_dateime but for my use case I wanted to store the ti...
New
JorisKok
I have a server on AWS, and was running a load test using artillery. When looking at the Phoenix dashboard I see the Ports going to 100% ...
New
earth10
Hi, I’m just starting to build a side-project with Elixir and Phoenix and doing some basic test with Elixir alone. What strikes me is th...
New

Other popular topics Top

New
shahryarjb
Hello, I have map which I want to convert it to string like this: the map: %{last_name: "tavakkoli", name: "shahryar"} the string I ne...
New
pmjoe
I have a relationship of love and hate with Elixir. Lots of things are just absolutely right, but there are some things that are kind of ...
New
msaraiva
Surface is an experimental library built on top of Phoenix LiveView and its new LiveComponent API that aims to provide a more declarative...
564 43757 214
New
belgoros
I’m not a pro in using Regex and can’t figure out why the following behaviour happens, especially if we take into account the difference ...
New
Qqwy
Original source of discussion: This topic on the Pragmatic Programmers’ Functional Web Development with Elixir, OTP, and Phoenix forum. ...
New
hariharasudhan94
I would like to know what is the best IDE for elixir development?
New
JakeBecker
TL;DR: I’ve just released an implementation of Microsoft’s IDE-independent Language Server Protocol for Elixir. It adds language support ...
1144 54120 245
New
dogweather
I wrote this comment on r/haskell, and it’s not popular there. :wink: But I think I’m on to something… Haskell reminds me of Java, and e...
New
svb
Hi! Currently I want to submit a form by pressing the Enter key. However, since my input field is of type “textarea” this is just adds a...
New

We're in Beta

About us Mission Statement