Rockson
Context / for request state equivalent
Hi I’m an absolute beginner trying to understand how to achieve the same thing I do with object oriented frameworks.
I can’t understand which is the recommended way to load some data at the start of the request that I can use later in my code without re-elaborating it every time. For example the authenticated user. I load it at the begin of the request, place it in a global store(aka context) and I can access it wherever I want since it is global.
Do I have to pass it using parameters? I don’t like the thing of polluting functions with it.
What does phoenix|elixir recommend?
Marked As Solved
gregvaughn
I think what you want to understand is the conn struct provided by Plug, which Phoenix builds atop. Plugs and plug pipelines can be used in your router to do things like authenticate a user and store that user in the conn struct so that once you resolve a particular controller/action you can access it.
However, you are expected to pass that sort of thing into functions lower-level in your business logic (Phoenix calls them “contexts”) where appropriate.
Also Liked
gregvaughn
I would offer to you the argument that is is not “pollution” for a function to accept a user parameter if it depends upon that user to perform its … function properly. That is called functional programming.
There are ways around it, but no, they are not common. What’s common is to have pure functions that take in all the params they need to achieve their function. Those are really easy to write tests for.
gregvaughn
A Repo is a GenServer. There’s macro sugar to make this less obvious. GenServers can have state. In this case there is a connection pool involved.
kokolegorille
Remember there are no objects, and FP does not share the same design patterns.
FP is about having pure functions. Everything is about (pure) composable functions…
Popular in Questions
Other popular topics
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
- #javascript
- #code-sync
- #podcasts
- #onsite
- #dialyzer
- #docker
- #authentication
- #umbrella
- #full-time-contract
- #podcasts-by-brainlid
- #ecto-query
- #elixir-ls
- #phoenix_html
- #iex
- #blog-post
- #graphql
- #genstage
- #ai
- #websockets
- #supervisor
- #advent-of-code
- #elixirconf-us
- #distillery
- #processes
- #forms
- #api
- #metaprogramming
- #security
- #performance








