benperiton
Hi,
I’m porting an old PHP application over to Elixir and Phoenix, and I’m struggling to figure out the best way to transfer the constants that currently exist.
At the moment there are multiple files with various constants used throughout the app, for instance:
<?php
namespace Shared\Consts;
class System
{
const AUDIT_ENTITY_REV_TYPE_DELETE = 301001;
const AUDIT_ENTITY_REV_TYPE_INSERT = 301002;
const AUDIT_ENTITY_REV_TYPE_UPDATE = 301003;
const AUDIT_LOG_ACTION_CREATE = 301004;
const AUDIT_LOG_ACTION_CUSTOM = 301005;
const AUDIT_LOG_ACTION_DELETE = 301006;
const AUDIT_LOG_ACTION_EDIT = 301007;
const SOURCE_LVL1_API = 301023;
const SOURCE_LVL1_HTTP = 301024;
const SOURCE_LVL1_EMAIL = 301025;
const SOURCE_LVL1_SMS = 301026;
const SOURCE_LVL1_UNKNOWN = 301027;
const SOURCE_LVL2_STAFF_PANEL = 301028;
const SOURCE_LVL2_STAFF_APP = 301029;
const SOURCE_LVL2_RESELLER_PANEL = 301030;
const SOURCE_LVL2_RESELLER_APP = 301031;
const SOURCE_LVL2_AFFILIATE_PANEL = 301032;
const SOURCE_LVL2_CUSTOMER_PANEL = 301033;
const SOURCE_LVL2_CUSTOMER_APP = 301034;
const SOURCE_LVL2_UNKNOWN = 301035;
}
Then in other files I can do:
<?php
use Shared\Const\System as SysConst;
if (SysConst::SOURCE_LVL1_API === $someOtherVariable)
{
echo 'Starts at API';
}
Is there a way to do something similar in Elixir? Or is there a better way to store lots of constants that could be the same name, but relate to different areas?
Trending in Questions
Hello!
Suppose you are building workflow (order / task / payment) processing system with the following requirements:
Each workflow con...
New
I’m in search of an Elixir library that offers PDF generation capabilities similar to Ruby’s Prawn. While there have been discussions abo...
New
I’m looking to build a personal workflow to quickly deploy web applications written in elixir/phoenix, for local consumption (ie not on t...
New
Before I dive in myself, did anyone successfully sprinkle Hologram into their existing LiveView app?
Looking for hints regarding:
Addi...
New
Kia ora,
We have been using elixir-google-api to connect to Google Drive. However, with the updates to Tesla due to CVEs this is now bro...
New
Hi all, I wanted to ask how the community is dealing with post-release steps.
Today we have Ecto migrations, which make sure that the db...
New
Hello,
I have an Elixir backend that implements a custom protocol over TCP. I want to load test the backend and assess the performance o...
New
Other Trending Topics
Hey, I’m Jesse and I’m the main contributor behind Dexter, a full-featured, lightning-fast Elixir LSP optimized for large codebases. It s...
New
Beam Bots (or just BB for short) is a framework for building fault-tolerant robotics applications in Elixir using familiar OTP patterns. ...
New
ExRatatui lets you cook up rich terminal UIs in Elixir, powered by Rust’s ratatui via Rustler NIFs. Build interactive terminal applicatio...
New
Hello everyone. After busy few months I am happy to announce v0.1.0 of Emerge & Solve.
They are GUI (Emerge) and State management (S...
New
Corex is an accessible, unstyled UI component library for Phoenix that integrates Zag.js state machines using Vanilla JavaScript and Live...
New
Emily is an Elixir library that runs Nx computations on Apple’s MLX. Install it as the default Nx backend and Nx, defn, Axon, Nx.Serving,...
New
Categories:
Sub Categories:
Forums
Popular Tags
- #ecto
- #liveview
- #troubleshooting
- #learning-elixir
- #deployment
- #library
- #erlang
- #testing
- #genserver
- #mix
- #absinthe
- #remote-other
- #otp
- #plug
- #how-to-question
- #macros
- #postgres
- #channels
- #elixirconf
- #exunit
- #discussion
- #code-sync
- #javascript
- #podcasts
- #onsite
- #dialyzer
- #docker
- #authentication
- #umbrella
- #full-time-contract
- #podcasts-by-brainlid
- #ecto-query
- #elixir-ls
- #blog-post
- #phoenix_html
- #iex
- #graphql
- #ai
- #genstage
- #elixirconf-us
- #websockets
- #supervisor
- #advent-of-code
- #distillery
- #processes
- #api
- #forms
- #metaprogramming
- #security
- #hex











Showing Posts 1 to 10- Show Best Posts
- Show All Posts (oldest first)
- Show All Posts (newest first)
michalmuskala
The usual approach would be to use atoms inside the system, e.g.
:source_lvl1_apiand convert to/from integer encoding on the system boundary, if needed. This makes it easy for debugging and introspection since at runtime you have readable atoms, instead of opaque integer values flying around. You can generate the conversion functions easily with a sprinkle of macros:OvermindDL1
You can also store it into a map that is returned from a function like this:
Being a constant object in the code with no variables it gets constructed fast, however usual things in Erlang/Elixir get optimized into the bytecode so no construction actually takes place and it gets shared easily, I’m not sure if maps do that however.
Overall @michalmuskala method is usually best, no construction time at all, however the lookup time can be linear in a match set like that so a map might be faster in lookup speed.
benperiton
Thanks both
So it looks like @OvermindDL1 idea of using a map would be the easiest way to get them across, but I’m intrigued by what you said @michalmuskala.
I’m not sure I fully grasp what you are suggesting, are you saying that the conversion would happen at the point that things are inserted and retrieved from the database? I’m struggling to figure out where those macros would live and how they would be used in other modules.
yurko
+1 to map solution since keyword list can have duplicate keys and with many constants it might become a problem down the way
smpallen99
I have a macro for reusing constants across multiple modules. The benefit being that they work in matches and in guards.
benperiton
This is quite cool! Would be nice if it was possible to require and alias at the same time, but I think I might have a play with this as the general way to do constants.
NobbZ
Well, in the “required” module you could implement a
__using__/1macro anduseit from the requiring one. In that__using__/1you then can of course require and alias at the same time.michalmuskala
Using such macros has still the same issue - you have opaque integers passing around at runtime - this makes it really hard to debug issues, especially if dealing with large numbers.
As to when do conversions - I spoke about boundaries of the system. By that I mean every time we receive data from outside or send it out - this means params from requests, database responses, etc. For example, when using ecto, you can provide a custom type to do the conversions for you (assuming
encodeanddecodefunctions as before):sasajuric
I would definitely go for the approach from @michalmuskala. One problem with maps is that it only supports one way conversion (converting a const into an integer). If you need to convert an integer into a const, you’ll have to build a reversal map. This can be easily done, even during compilation time, but then the code becomes as complex if not more than Michal’s version.
Moreover, I’m not completely sure whether this map is stored in the so called “constant pool”, and if it’s not, then the performance might suck. But even if this is not the case, my previous point stands, and I would personally go for Michal’s solution.
Using that approach, you could have something like:
And now you can do e.g.
Const.encode(:source_lvl1_api), orConst.decode(301023)to perform atom ↔ integer conversions.So what Michal is trying to tell you is that as soon as you take some input from say HTTP request, or the database, you invoke
Const.decodeto convert it into an atom. Then in the rest of your code, you just deal with atoms (e.g.:source_lvl1_api), so the code is ridden of magical numbers. Likewise, if you need to send a response to some client, or store to the database, you performConst.encodeto convert the atom into a corresponding integer.benperiton
I ended up going with the idea from @michalmuskala - it makes sense to use atoms everywhere I can, then just have integers in the DB and frontend client.
I decided to have a folder of JSON files, that way I can easily use it on the frontend as well (at the moment it runs some scripts to convert to JSON files from PHP)
Are there any issues doing it this way?
I was thinking of prepending the name of the file to each key in the JSON file to help namespace it a bit, so system.json would be
and would end up being
Not sure though!