5
votes

When writing Phoenix apps I've gotten used to writing links using a syntax like this: link "My profile", to: Routes.user_url(@conn, :show, user). Recently when working with LiveView I realized that you can pass MyAppWeb.Endpoint instead of @conn here, and it will work the same. Since (I imagine) most Phoenix apps only have a single Endpoint module, I kinda wish that it would infer my default Endpoint so that I don't have to provide the conn/endpoint every single time I call a path/url helper. And it makes me wonder why Phoenix designed these helpers to always require the endpoint, instead of using some configured default endpoint.

Does anyone know why the route helpers were designed to always require a conn/endpoint, and don't allow you to configure a default endpoint? Is it simply a matter of "haven't gotten around to that yet", or is there some important reason why it would be problematic to not explicitly require the conn/endpoint every time?

1
I do not know for certain, but I would guess that part of the reason comes from Elixir's philosophy of "explicit over implicit". You may have to type a handful of extra characters, but you will not accidentally change all of your routes by making a config change.Justin Wood
I believe Chris McCord's answers in this thread is what you're looking for: elixirforum.com/t/conn-or-endpoint-in-path-helpers/934Konstantin Strukov

1 Answers

6
votes

The connection has additional information beyond the endpoint. For example, if you have two routers in your application, where one calls the other, you need to be able to assemble the original path back together (this is typically called script_name for CGI legacy reasons). Also, new APIs such as put_router_uri allow you to to store in the connection which base URI to use in a given request, for example if you want to set a subdomain for the currently logged in user, and this information cannot be global.