Hide various implementations behind a common interface in erlang

I have an erlang code snippet that should read some values ​​from db and should support a couple of dbs. I wanted my code somehow not to depend on db, so I implemented two different gen_servers that register both with the same atom (db_handler). I decide which version should be running to read the .app file.

Two gen_servers set a common handle_call, so I can use something like the other parts of my application:

gen_server:call(db_handler, {do_something, "value1", "value2"})

This works, but still it is closely related to the fact that each and every future implementation for the new db should be gen_server.

I was thinking about using it! operator and process the command in handle_info, but still I believe that a better solution is possible (perhaps through another module?).

Can someone give me some idea of ​​a better way to deal with something like this in erlang?

+4
source share
2 answers

For each db server, add a common interface for the abstract call:

-module(db_server1).

...

do_something([Value1,Value2]) -> gen_server:call(db_handler, {do_something, "value1", "value2"}).

...

another not using gen server

-module(db_server2).

...

do_something([Value1,Value2]) -> something_else({do_something, "value1", "value2"}).

...

create a new process (gen_server: o) that receives as an init parameter a parameter that is used to select the db server and saves it in its state (for example, db_server2),

for each do_something function, implement a function such as:

do_something(Value1,Value2) -> gen_server:call(db_handler, {do_something, ["value1", "value2"]}).

...

handle_call({Func, Args}, _From, DB_server) ->
    R = DB_server:F(Args),
    {reply, R, DB_server}.

same for non-blocking interfaces using cast or equivalent

+2
source

Each database driver can be a library module that provides functions for your gen_server.

handle_call({do_something, Driver, Value1, Value2}, _From, State) ->
  Reply = Driver:do_something(Value1, Value2),
  {reply, Reply, State}.
0
source

Source: https://habr.com/ru/post/1535820/


All Articles