Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Elixir / Phoenix: Why do route helpers require @conn?

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?

like image 626
Topher Hunt Avatar asked Jun 21 '19 10:06

Topher Hunt


1 Answers

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.

like image 61
José Valim Avatar answered Oct 02 '22 11:10

José Valim